算法參數
- 算法:DES/CBC/PKCS5Padding
- 密鑰:8 字節(示例 "abcdefghijk" 截取前 8 位)
- IV:固定 8 字節
{0x12,0x34,0x56,0x78,0x90,0xAB,0xCD,0xEF}
- 輸出:Base64 編碼便於傳輸存儲
工具類核心代碼
public class DESUtil {
private Key key;
private AlgorithmParameterSpec iv;
public DESUtil() throws Exception {
byte[] keyBytes = "abcdefghijk".getBytes(StandardCharsets.UTF_8);
DESKeySpec keySpec = new DESKeySpec(Arrays.copyOf(keyBytes, 8));
iv = new IvParameterSpec(new byte[]{0x12,0x34,0x56,0x78,(byte)0x90,(byte)0xAB,(byte)0xCD,(byte)0xEF});
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
key = factory.generateSecret(keySpec);
}
public String getEnc(String plain) {
byte[] encrypted = cipherDoFinal(plain.getBytes(StandardCharsets.UTF_8), Cipher.ENCRYPT_MODE);
return Base64.getEncoder().encodeToString(encrypted);
}
public String getDec(String cipherText) {
byte[] decoded = Base64.getDecoder().decode(cipherText);
byte[] decrypted = cipherDoFinal(decoded, Cipher.DECRYPT_MODE);
return new String(decrypted, StandardCharsets.UTF_8);
}
private byte[] cipherDoFinal(byte[] input, int mode) {
try {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(mode, key, iv);
return cipher.doFinal(input);
} catch (Exception e) { throw new RuntimeException(e); }
}
}
測試驗證
DESUtil util = new DESUtil();
String encrypted = util.getEnc("I love you");
String decrypted = util.getDec(encrypted);
assert "I love you".equals(decrypted);
安全性提醒
- DES 已不安全:56 位有效密鑰可暴力破解,生產環境**強制使用 AES-256-GCM**
- 密鑰管理:勿硬編碼,使用 KMS/配置中心注入
- IV 唯一性:CBC 模式每次加密應生成隨機 IV,隨密文存儲
- 完整性:引入 HMAC 或使用 AEAD 模式(GCM/CCM)
現代替代方案
// AES-GCM 示例
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, ivBytes); // 128-bit tag
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec);
byte[] cipherText = cipher.doFinal(plainBytes); // 含認證標簽