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

Java 加解密工具類:AES、DES、TripleDES 完整實現與性能對比

     編輯:Java 綜合教學

Java 加解密工具類:AES、DES、TripleDES 完整實現與性能對比

核心工具類 EncryptUtil

public class EncryptUtil {
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final int AES_KEY_SIZE = 16; // 128-bit
    
    // ========== AES ==========
    private static final String AES_ALGO = "AES";
    private static final String AES_CIPHER = "AES/CBC/PKCS5Padding";
    
    public static String aesEncrypt(String src, String key) { ... }
    public static String aesDecrypt(String src, String key) { ... }
    private static byte[] getAESResult(String key, byte[] data, int mode) { ... }
    
    // ========== TripleDES (DESede) ==========
    private static final String TRIPLE_DES_ALGO = "DESede";
    private static final String TRIPLE_DES_CIPHER = "DESede/ECB/PKCS5Padding";
    
    public static String tripleDesEncrypt(String src, String key) { ... }
    public static String tripleDesDecrypt(String src, String key) { ... }
    private static byte[] getTripleDESResult(String key, byte[] data, int mode) { ... }
    
    // ========== DES ==========
    private static final String DES_ALGO = "DES";
    private static final String DES_CIPHER = "DES";
    
    public static String desEncrypt(String src, String key) { ... }
    public static String desDecrypt(String src, String key) { ... }
    private static byte[] getDESResult(String key, byte[] data, int mode) { ... }
    
    // ========== 密鑰規範化 ==========
    private static byte[] buildCLenKey(String keyStr, int len) throws UnsupportedEncodingException {
        byte[] key = new byte[len];
        byte[] temp = keyStr.getBytes("UTF-8");
        System.arraycopy(temp, 0, key, 0, Math.min(temp.length, len));
        return key; // 不足補0,超出截斷
    }
}

關鍵實現細節

  • AES:CBC 模式 + PKCS5Padding,需 IV(此處用 SecureRandom 隨機),密鑰 16/24/32 字節
  • TripleDES:ECB 模式(無 IV),密鑰 24 字節(3×8),兼容性好但較慢
  • DES:單 DES,密鑰 8 字節,**不安全,僅用於兼容舊系統**
  • 統一 Base64 編碼 密文輸出(Base64.getEncoder/Decoder Java 8+)
  • 密鑰統一由 buildCLenKey 截斷/補零適配長度

性能基準測試 (10 萬次循環)

Key: !@#$%^&*()_+  Src: ~80字符
TripleDES: 3831 ms  (0.038 ms/op)
DES:        845 ms  (0.008 ms/op)
AES:        888 ms  (0.009 ms/op)

結論: DES 最快但極不安全;AES 安全性能平衡,**推薦生產環境首選 AES-128-CBC**;TripleDES 僅用於老系統對接。

完整代碼見正文(含 main 測試方法)

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