雖然 AES 已成為對稱加密標準,但 DES 在舊系統維護、嵌入式裝置、低安全性場景仍有應用空間。本文提供最精簡的 Java DES 實作,剔除冗長的編碼轉換、長度判斷等非核心邏輯,聚焦於「演算法本身」。
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
public class ComCipher {
private final byte[] desKey = new byte[8]; // DES 固定 8 位元組金鑰
private final byte[] desIv = new byte[8]; // CBC 模式需 8 位元組 IV
private Cipher cipher;
private SecretKey secretKey;
private IvParameterSpec ivSpec;
private final SecureRandom random = new SecureRandom();
public ComCipher() {
// 示範用固定金鑰/IV,實務請用 PBKDF2 衍生
for (int i = 0; i < 8; i++) {
desKey[i] = 0x01;
desIv[i] = 0x00;
}
}
public void init() throws Exception {
DESKeySpec keySpec = new DESKeySpec(desKey);
SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
secretKey = factory.generateSecret(keySpec);
ivSpec = new IvParameterSpec(desIv);
// CBC + NoPadding:資料長度必須為 8 位元組倍數
cipher = Cipher.getInstance("DES/CBC/NoPadding");
}
// 加密
public byte[] encrypt(byte[] plaintext) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec, random);
return cipher.doFinal(plaintext);
}
// 解密
public byte[] decrypt(byte[] ciphertext) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec, random);
return cipher.doFinal(ciphertext);
}
}
public static void main(String[] args) {
try {
ComCipher cipher = new ComCipher();
cipher.init();
// 測試資料:正好 8 位元組(NoPadding 要求)
byte[] input = new byte[8];
for (int i = 0; i < 8; i++) input[i] = 0x01;
System.out.println("原文: " + bytesToHex(input));
byte[] encrypted = cipher.encrypt(input);
System.out.println("密文: " + bytesToHex(encrypted));
byte[] decrypted = cipher.decrypt(encrypted);
System.out.println("解密: " + bytesToHex(decrypted));
} catch (Exception e) {
e.printStackTrace();
}
}
// 輔助:byte[] 轉十六進位字串
private static String bytesToHex(byte[] data) {
StringBuilder sb = new StringBuilder();
for (byte b : data) sb.append(String.format("%02X", b));
return sb.toString();
}
| 項目 | 設定值 | 備註 |
|---|---|---|
| 演算法 | DES | 56-bit 有效金鑰,已不建議用於高機密資料 |
| 模式 | CBC | 需初始化向量 (IV),比 ECB 安全 |
| 填充 | NoPadding | 資料長度必須為 8 的倍數;改用 PKCS5Padding 可支援任意長度 |
| 金鑰長度 | 8 bytes (64 bits) | 含 8 位 parity bits,實際強度 56 bits |
| IV 長度 | 8 bytes | CBC 模式必須 |
DES/CBC/PKCS5Padding,並移除長度限制檢查掌握 DES 核心流程,有助於理解區塊加密基本原理,維護舊系統時也能得心應手。