import java.security.Key;
import java.util.Date;
import javax.crypto.Cipher;
public class DESEncrypt {
private static Key getKey(byte[] arrBTmp) throws Exception {
// 創建一個空的8位字節數組(默認值爲0)
byte[] arrB = new byte[8];
// 將原始字節數組轉換爲8位
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
// 生成密鑰
Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key;
}
public static byte[] encrypt(byte[] contentBytes, byte[] keyBytes) {
byte[] hasEncrypt = null;
try {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, getKey(keyBytes));
hasEncrypt = cipher.doFinal(contentBytes);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return hasEncrypt;
}
public static byte[] decrypt(byte[] contentBytes, byte[] keyBytes) {
byte[] hasDecrypt = null;
try {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, getKey(keyBytes));
hasDecrypt = cipher.doFinal(contentBytes);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return hasDecrypt;
}
}
Test:
String content = "DES加密";
String uuid = UUID.randomUUID().toString();
String a = Base64.encodeBytes(DESEncrypt.encrypt(content.getBytes("UTF-8"),uuid.getBytes("UTF-8")));
System.out.println("DES Encrypt..." + a);
//先Base64解碼,再DES解密
String b = new String(DESEncrypt.decrypt(Base64.decode(a), uuid.getBytes("UTF-8")),"UTF-8");
System.out.println("DES decrypt..." + b);
Console
DES Encrypt...hqPYNk/ewpBdzaxNm4tqDQ==
DES decrypt...DES加密