import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2017/9/28 0028.
* key.obj文件作为加密的秘钥
* file 为要加密的文件
*/
public class MyDESPlus {
public static int MODE_EXPRESSLY = 0;
public static int MODE_GAEBLED = 1;
public int c = 0;
private Cipher enCipher = null;
public MyDESPlus() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
this.enCipher = Cipher.getInstance("DES");
this.enCipher.init(1, intiPriveKey("key.obj"));
}
/**
* ip.properties 文件加密处理
* key.obj文件作为加密的秘钥
* file 为要加密的文件
*/
public static void jiami(File keyObj,File file) throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 获得密匙数据
// FileInputStream fi = new FileInputStream(new File("key.obj"));
FileInputStream fi = new FileInputStream(keyObj);
byte rawKeyData[] = new byte[fi.available()];
fi.read(rawKeyData);
fi.close();
// 从原始密匙数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(rawKeyData);
// 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
// 现在,获取要加密的文件数据
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //12
FileInputStream fi2 = new FileInputStream(file);
byte data[] = new byte[fi2.available()];
fi2.read(data);
// 正式执行加密操作
byte encryptedData[] = cipher.doFinal(data);
baos.write(encryptedData);
fi2.close();
if(file.delete()){
// 用加密后的数据覆盖原文件
file.createNewFile();
String filename = file.getName();
FileOutputStream fos = new FileOutputStream(file);
fos.write(byteArr2HexStr(baos.toByteArray()).getBytes()); //12
fos.flush();
fos.close();
}
}
public static String byteArr2HexStr(byte[] buff) {
@SuppressWarnings("StringBufferMayBeStringBuilder")
StringBuffer sb = new StringBuffer(buff.length * 2);
for (int i = 0; i < buff.length; i++) {
int b = buff[i];
while (b < 0) {
b += 256;
}
if (b < 16) sb.append("0");
sb.append(Integer.toHexString(b));
}
return sb.toString();
}
private byte[] hexStr2BtyeArr(String str) {
byte[] buff = new byte[str.length() / 2];
byte[] b = str.getBytes();
for (int i = 0; i < str.length(); i += 2) {
String temp = new String(b, i, 2);
buff[(i / 2)] = ((byte)Integer.parseInt(temp, 16));
}
return buff;
}
private Key intiPriveKey(String key) throws IOException, NoSuchAlgorithmException
{
File keyF = new File(key);
if (keyF.exists()) keyF.delete();
keyF.createNewFile();
FileOutputStream fos = new FileOutputStream(keyF);
KeyGenerator keyG = KeyGenerator.getInstance("DES");
keyG.init(56);
Key k = keyG.generateKey();
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(k);
oos.close();
return k;
}
//把类文件加密后存到decript.cipher文件
public void encrypt(File classFile) throws IllegalBlockSizeException, BadPaddingException, IOException {
if ((classFile == null) || (!classFile.exists())) return;
if (!classFile.getName().endsWith(".class")) return;
byte[] enByte = this.enCipher.doFinal(getBytes2ClassFile(classFile));
FileOutputStream fos = new FileOutputStream(getClass2Cipher(classFile.getAbsolutePath()));
fos.write(enByte);
fos.close();
classFile.delete();
}
private byte[] getBytes2ClassFile(File file) throws IOException {
long len = file.length();
byte[] data = new byte[(int)len];
FileInputStream fin = new FileInputStream(file);
int r = fin.read(data);
if (r != len)
throw new IOException("Only read " + r + " of " + len + " for " + file);
fin.close();
return data;
}
private String getClass2Cipher(String fileName) {
if (fileName.endsWith(".class")) {
return fileName.substring(0, fileName.indexOf(".class")) + ".cipher";
}
return null;
}
@SuppressWarnings("CallToPrintStackTrace")
public void encryptWEB(String domain, List<String> ips, Map maps, String targetDir){
try {
encrypt(new File(targetDir + "/WEB-INF/classes/org/springframework/decript/Decript.class"));
/* jiami(new File(targetDir+"/WEB-INF/classes/db.properties")); //对数据库文件加密
jiami(new File(targetDir+"/WEB-INF/classes/service.xml")); //对配置文件 加密
jiami(new File(targetDir+"/WEB-INF/classes/config/select.data"));*/
maps.put("domain", domain);
maps.put("ips", ips);
Data da = new Data();
da.setMap(maps);
da.setCDKEY(MD5.MD5Encode(domain));
obj2File(da, "data.obj");
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("ConvertToTryWithResources")
public Object obj2File(Object obj, String filepath) throws IOException {
File file = new File(filepath);
if (!file.exists()) file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
fos.close();
oos.close();
return obj;
}
}
转载于:https://www.cnblogs.com/fgh2018/p/9408858.html