DES(Data Encryption Standard)是經典對稱加密算法,雖然密鑰長度較短(56 位),在高安全性場景已被 AES 取代,但在舊系統維護、輕量級數據混淆、教學演示中仍有應用。本文提供基於 JDK javax.crypto 的完整 DES 工具類,支持 CBC 模式、PKCS5Padding、文件與字符串雙模式加解密。
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
import java.security.SecureRandom;
public class DesTool {
// 密鑰:8 字節(DES 固定)
private static final String DES_KEY = "asfsdfsdf";
// IV 向量:8 字節(CBC 模式必需)
private static final String IV_PARAM = "afasdf";
/** 文件加密/解密 */
public static String encryptOrDecryptFile(String filePath, String fileName, int mode) {
InputStream is = null;
OutputStream os = null;
CipherInputStream cis = null;
try {
// 1. 構建密鑰
DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
SecretKey key = kf.generateSecret(dks);
// 2. 初始化 Cipher
IvParameterSpec iv = new IvParameterSpec(IV_PARAM.getBytes());
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(mode, key, iv, new SecureRandom());
// 3. 文件流處理
File inFile = new File(filePath, fileName);
File outDir = new File(filePath, "encrypted");
if (!outDir.exists()) outDir.mkdirs();
File outFile = new File(outDir, fileName);
is = new FileInputStream(inFile);
os = new FileOutputStream(outFile);
cis = new CipherInputStream(is, cipher);
byte[] buffer = new byte[1024];
int len;
while ((len = cis.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
return outFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
closeQuietly(is, cis, os);
}
}
/** 字符串加密/解密 */
public static String encryptOrDecryptString(String src, int mode) {
try {
DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
SecretKey key = kf.generateSecret(dks);
IvParameterSpec iv = new IvParameterSpec(IV_PARAM.getBytes());
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(mode, key, iv, new SecureRandom());
CipherInputStream cis = new CipherInputStream(
new ByteArrayInputStream(src.getBytes()), cipher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = cis.read(buffer)) > 0) {
baos.write(buffer, 0, len);
}
return baos.toString(); // 注意:解密後需指定編碼 new String(bytes, "UTF-8")
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// 安全關閉資源
private static void closeQuietly(Closeable... closeables) {
for (Closeable c : closeables) {
if (c != null) try { c.close(); } catch (IOException ignored) {}
}
}
// 測試
public static void main(String[] args) {
String original = "敏感數據:用戶ID=10086";
System.out.println("原文: " + original);
String encrypted = encryptOrDecryptString(original, Cipher.ENCRYPT_MODE);
System.out.println("加密: " + encrypted); // 亂碼/二進制字符串
String decrypted = encryptOrDecryptString(encrypted, Cipher.DECRYPT_MODE);
System.out.println("解密: " + decrypted);
}
}
| 參數 | 值 | 說明 |
|---|---|---|
| 算法/模式/填充 | DES/CBC/PKCS5Padding | CBC 模式需 IV,PKCS5 填充至 8 字節倍數 |
| 密鑰長度 | 8 字節 (56 位有效) | DES 固定,不足補齊,超出截取 |
| IV 長度 | 8 字節 | CBC 模式必需,建議隨機生成並隨密文傳輸 |
| SecureRandom | 加密隨機源 | 增強安全性 |
BadPaddingException、IllegalBlockSizeException 區分密鑰錯誤/數據損壞// 僅需修改算法名與密鑰長度
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); // 推薦 GCM 認證加密
SecretKeySpec keySpec = new SecretKeySpec(aesKeyBytes, "AES"); // 32 字節密鑰
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, ivBytes); // 12 字節 IV
cipher.init(mode, keySpec, gcmSpec);
理解 DES 算法結構、CBC 模式、填充機制、IV 作用,是掌握現代對稱加密(AES、ChaCha20)的基石。工程中請堅決遷移至 AES-GCM 或 ChaCha20-Poly1305。