public String getRandomString(final int size) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
Random random = new Random();
StringBuffer randomBuffer = new StringBuffer();
int index = 0;
int valueIndex;
while (index < size) {
valueIndex = random.nextInt(16);
randomBuffer.append(hexDigits[valueIndex]);
index++;
}
// System.out.println(randomBuffer.toString());
return randomBuffer.toString();
}
public void doDESTest() {
String content = getRandomString(1 << 10);
String password = getRandomString(16);
System.out.println(content);
byte encrypt[] = desEncrypt(content.getBytes(), password);
if (encrypt != null) {
System.out.println(new String(encrypt));
byte src[] = desDecrypt(encrypt, password);
System.out.println(new String(src));
}
}
public byte[] desEncrypt(byte[] datasource, String password) {
try {
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
// 现在,获取数据并加密
// 正式执行加密操作
return cipher.doFinal(datasource);
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
private byte[] desDecrypt(byte[] src, String password) {
// DES算法要求有一个可信任的随机数源
SecureRandom random = new SecureRandom();
try {
// 创建一个DESKeySpec对象
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 将DESKeySpec对象转换成SecretKey对象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正开始解密操作
return cipher.doFinal(src);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}