import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
*
* @author Yuanyuan
*/
public class Test
{
public void createKey(String keyName) throws Exception {
// 创建一个可信任的随机数源,DES算法需要
SecureRandom sr = new SecureRandom();
// 用DES算法创建一个KeyGenerator对象
KeyGenerator kg = KeyGenerator.getInstance("DES");
// 初始化此密钥生成器,使其具有确定的密钥长度
kg.init(sr);
// 生成密匙
SecretKey key = kg.generateKey();
// 获取密钥数据
byte rawKeyData[] = key.getEncoded();
// 将获取到密钥数据保存到文件中,待解密时使用
FileOutputStream fo = new FileOutputStream(new File(keyName));
fo.write(rawKeyData);
}
public void entrypted() throws Exception
{
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 获得密匙数据
FileInputStream fi = new FileInputStream(new File("key.txt"));
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);
// 现在,获取要加密的文件数据
FileInputStream fi2 = new FileInputStream(new File("ciphertext.txt"));
byte data[] = new byte[fi2.available()];
fi2.read(data);
fi2.close();
// 正式执行加密操作
byte encryptedData[] = cipher.doFinal(data);
// 用加密后的数据覆盖原文件
FileOutputStream fo = new FileOutputStream(new File("ciphertext.txt"));
fo.write(encryptedData);
fo.close();
}
public void decryped()throws Exception
{
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 获得密匙数据
FileInputStream fi = new FileInputStream(new File("key.txt"));
byte rawKeyData[] = new byte[fi.available()];// = new byte[5];
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.DECRYPT_MODE, key, sr);
// 现在,获取数据并解密
FileInputStream fi2 = new FileInputStream(new File("ciphertext.txt"));
byte encryptedData[] = new byte[fi2.available()];
fi2.read(encryptedData);
fi2.close();
// 正式执行解密操作
byte decryptedData[] = cipher.doFinal(encryptedData);
// 这时把数据还原成原有的类文件
FileOutputStream fo = new FileOutputStream(new File("palintext.txt"));
fo.write(decryptedData);
}
public static void main(String args[])
{
try
{
//1.生成秘钥文件key.txt
Test keyGentor = new Test();
keyGentor.createKey("key.txt");
System.out.println("生成秘钥文件key.txt");
//2.用这个密匙文件Key.txt对我们指定的文件进行加密
keyGentor.entrypted();
System.out.println("对ciphertext.txt文件内容加密");
//3.
keyGentor.decryped();
System.out.println("解密到plaintext.txt");
} catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
//其他通用方法
private void writeLog(PrintWriter pw, String content)
{
pw.write(content);
pw.println();
pw.flush();
}
//加密,String明文输入,String密文输出
private String getEncString(Key key, String strMing) throws Exception
{
String strMi = "";
try
{
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] byteFina = cipher.doFinal(strMing.getBytes());
String hs = "";
String stmp = "";
for (int n = 0; n < byteFina.length; n++)
{
//整数转成十六进制表示
stmp = (Integer.toHexString(byteFina[n] & 0XFF));
if (stmp.length() == 1)
{
hs = hs + "0" + stmp;
} else
{
hs = hs + stmp;
}
}
strMi = hs.toUpperCase();
//strMi = byte2hex(getEncCode(strMing.getBytes()));
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e)
{
logger.error(e.getMessage());
throw new Exception(e);
}
return strMi;
}
//解密,以String密文输入,String明文输出
private String getDesString(Key key, String strMi) throws Exception
{
String strMing = "";
try
{
byte[] b = strMi.getBytes();
if ((b.length % 2) != 0)
{
throw new IllegalArgumentException("长度不是偶数");
}
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2)
{
String item = new String(b, n, 2);
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个进制字节
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] byteFina = cipher.doFinal(b2);
strMing = new String(byteFina);
//strMing = new String(getDesCode(hex2byte(strMi.getBytes())));
} catch (IllegalArgumentException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e)
{
logger.error(e.getMessage());
throw new Exception(e);
}
return strMing;
}
//将明文string,加密后存储到文件中。
public void saveStringToFile(Key key, PrintWriter pw, String content) throws Exception
{
// File logFile = new File(filePath);
// if (!logFile.exists())
// {
// System.out.println("log.txt file no exist, create one.");
// logFile.createNewFile();
// }
// PrintWriter pw = new PrintWriter(logFile);
String strEnc = getEncString(key, content);//加密字符串,返回String的密文
writeLog(pw, strEnc);
System.out.println("密文 = " + strEnc);
}
//读取并解析文件中的密文为明文
public void readStringFromEncryptedFile(Key key, String filePath) throws Exception
{
File logFile = new File(filePath);
if (!logFile.exists())
{
System.out.println("log.txt file no exist, read nothing.");
return;
}
FileInputStream fis = new FileInputStream(logFile);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
//解析文件
String line = "";
while ((line = br.readLine()) != null)
{
String strDes = getDesString(key, line);//把String类型的密文解密
System.out.println("明文 = " + strDes);
}
}
转载于:https://my.oschina.net/liuyuanyuangogo/blog/372655