本文提供一個基於 JDK javax.crypto 實現的 DES 加密/解密工具類,採用 ECB 模式、PKCS5Padding 填充,密鑰派生自業務代碼 + 固定鹽值,結果經 Base64 編碼便於傳輸。
package com.eabax.plugin.yundada.utils;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
public class DESEncryptHelper {
private static final String ALGO = "DES";
/** 從緩存或生成密鑰:業務代碼 + 固定鹽值 */
public static String getDESKey(String encryptStr) {
// 實際項目建議使用成熟緩存框架(Caffeine/Redis)替代簡單 Map
return encryptStr + "tablemiyaokey"; // 簡化演示
}
/** 加密入口:字符串 → Base64 密文 */
public static String encrypt(String plainText, String encryptStr)
throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException {
String key = getDESKey(encryptStr);
SecretKey secretKey = generateSecretKey(key);
Cipher cipher = Cipher.getInstance(ALGO); // 默認 ECB/PKCS5Padding
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherBytes = cipher.doFinal(plainText.getBytes());
return new String(Base64.encodeBase64(cipherBytes));
}
/** 解密入口:Base64 密文 → 明文字符串 */
public static String decrypt(String cipherText, String encryptStr)
throws Exception {
if (cipherText == null) return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] cipherBytes = decoder.decodeBuffer(cipherText);
String key = getDESKey(encryptStr);
SecretKey secretKey = generateSecretKey(key);
Cipher cipher = Cipher.getInstance(ALGO);
SecureRandom sr = new SecureRandom();
cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
byte[] plainBytes = cipher.doFinal(cipherBytes);
return new String(plainBytes);
}
/** 從字符串生成 DES SecretKey */
private static SecretKey generateSecretKey(String keyStr)
throws NoSuchAlgorithmException, InvalidKeySpecException {
DESKeySpec keySpec = new DESKeySpec(keyStr.getBytes());
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGO);
return factory.generateSecret(keySpec);
}
}
Cipher.getInstance("DES") 等價 "DES/ECB/PKCS5Padding"。Apache Commons Codec 與 sun.misc.BASE64Decoder,建議統一使用 java.util.Base64 (Java 8+)。加密解密涉及多種受檢異常(InvalidKeyException、NoSuchAlgorithmException 等),建議封裝為運行時異常或統一業務異常向上拋出。
PBKDF2WithHmacSHA256、迭代 100,000+ 從主密鑰派生數據加密鍵 (DEK)。java.util.Base64 替代內部類/第三方庫。本工具類演示了 DES 基礎 API 用法,但不適合直接用於生產敏感數據。請務必遵循現代密碼學最佳實踐,選用 AES-GCM、合規密鑰管理、認證加密,守護數據機密性與完整性。