首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java DES 對稱加密解密工具類實現詳解

     編輯:Java 相關知識

概述

本文提供一個基於 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);
    }
}

關鍵技術點解析

1. DES 算法特性

  • 密鑰長度 56 位(+8 位校驗),分組長度 64 位。
  • 現代標準視為不安全(可暴力破解),生產環境強烈建議改用 AES-256-GCM。

2. 模式與填充

  • Cipher.getInstance("DES") 等價 "DES/ECB/PKCS5Padding"。
  • ECB 模式無 IV,相同明文產生相同密文,不安全;CBC/GCM 模式需隨機 IV。

3. 密鑰管理

  • 示例中密鑰由業務字段拼接固定字符串生成,極不安全。正規項目應:
      • 使用 PBKDF2/Argon2 從密碼派生密鑰。
      • 密鑰輪換、分級管理、HSM 存儲。
      • 密鑰與數據分離存儲。

4. Base64 編碼

  • 加密輸出二進制不可直接傳輸,需 Base64 編碼為字符串。
  • 解密前先 Base64 解碼。示例混用 Apache Commons Codec 與 sun.misc.BASE64Decoder,建議統一使用 java.util.Base64 (Java 8+)。

5. 異常處理

加密解密涉及多種受檢異常(InvalidKeyException、NoSuchAlgorithmException 等),建議封裝為運行時異常或統一業務異常向上拋出。

安全增強清單(生產必做)

  1. 替換為 AES-256-GCM(認證加密,防篡改)。
  2. 每次加密生成隨機 12 字節 IV/Nonce,隨密文輸出。
  3. 使用 PBKDF2WithHmacSHA256、迭代 100,000+ 從主密鑰派生數據加密鍵 (DEK)。
  4. 引入 java.util.Base64 替代內部類/第三方庫。
  5. 密鑰存儲於 Vault/KMS,代碼中不出現明文密鑰。

總結

本工具類演示了 DES 基礎 API 用法,但不適合直接用於生產敏感數據。請務必遵循現代密碼學最佳實踐,選用 AES-GCM、合規密鑰管理、認證加密,守護數據機密性與完整性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved