EncryptUtilpublic class EncryptUtil {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final int AES_KEY_SIZE = 16; // 128-bit
// ========== AES ==========
private static final String AES_ALGO = "AES";
private static final String AES_CIPHER = "AES/CBC/PKCS5Padding";
public static String aesEncrypt(String src, String key) { ... }
public static String aesDecrypt(String src, String key) { ... }
private static byte[] getAESResult(String key, byte[] data, int mode) { ... }
// ========== TripleDES (DESede) ==========
private static final String TRIPLE_DES_ALGO = "DESede";
private static final String TRIPLE_DES_CIPHER = "DESede/ECB/PKCS5Padding";
public static String tripleDesEncrypt(String src, String key) { ... }
public static String tripleDesDecrypt(String src, String key) { ... }
private static byte[] getTripleDESResult(String key, byte[] data, int mode) { ... }
// ========== DES ==========
private static final String DES_ALGO = "DES";
private static final String DES_CIPHER = "DES";
public static String desEncrypt(String src, String key) { ... }
public static String desDecrypt(String src, String key) { ... }
private static byte[] getDESResult(String key, byte[] data, int mode) { ... }
// ========== 密鑰規範化 ==========
private static byte[] buildCLenKey(String keyStr, int len) throws UnsupportedEncodingException {
byte[] key = new byte[len];
byte[] temp = keyStr.getBytes("UTF-8");
System.arraycopy(temp, 0, key, 0, Math.min(temp.length, len));
return key; // 不足補0,超出截斷
}
}
SecureRandom 隨機),密鑰 16/24/32 字節Base64.getEncoder/Decoder Java 8+)buildCLenKey 截斷/補零適配長度Key: !@#$%^&*()_+ Src: ~80字符 TripleDES: 3831 ms (0.038 ms/op) DES: 845 ms (0.008 ms/op) AES: 888 ms (0.009 ms/op)
結論: DES 最快但極不安全;AES 安全性能平衡,**推薦生產環境首選 AES-128-CBC**;TripleDES 僅用於老系統對接。