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

AES 加密解密工具類:ECB/PKCS5Padding 模式完整實現

     編輯:Java 綜合教學

AES 加密解密工具類:ECB/PKCS5Padding 模式完整實現

AES (Advanced Encryption Standard) 是當前最廣泛使用的對稱加密算法。本工具類封裝了 AES-128-ECB-PKCS5Padding 模式,提供二進制/十六進制輸出格式,適合 API 簽名、敏感配置加密、Token 生成等場景。

算法參數

  • 算法:AES
  • 模式:ECB (Electronic Codebook)
  • 填充:PKCS5Padding (等同 PKCS7Padding,填充字節值 = 填充長度)
  • 密鑰長度:128 位 (16 字節)
  • 編碼:UTF-8

⚠️ 安全提示:ECB 模式不引入初始化向量 (IV),相同明文加密結果固定,不適合加密大量結構化數據(如圖片、文檔、長文本)。生產環境敏感數據請使用 CBC/GCM 模式並妥善管理 IV。

核心代碼:AESCode.java

package com.test;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.security.spec.InvalidKeySpecException;

public class AESCode {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    private static final String CHARSET = "UTF-8";

    /** 從用戶密碼派生 128 位密鑰 */
    private static SecretKeySpec deriveKey(String password) {
        try {
            KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
            kg.init(128, new SecureRandom(password.getBytes(CHARSET)));
            SecretKey sk = kg.generateKey();
            return new SecretKeySpec(sk.getEncoded(), ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("AES 算法不可用", e);
        }
    }

    /** 核心加密:返回原始字節數組 */
    private static byte[] encryptBytes(String content, String password) {
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, deriveKey(password));
            return cipher.doFinal(content.getBytes(CHARSET));
        } catch (GeneralSecurityException | UnsupportedEncodingException e) {
            throw new RuntimeException("加密失敗", e);
        }
    }

    /** 核心解密:輸入原始字節數組 */
    private static String decryptBytes(byte[] cipherBytes, String password) {
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, deriveKey(password));
            byte[] plain = cipher.doFinal(cipherBytes);
            return new String(plain, CHARSET);
        } catch (GeneralSecurityException | UnsupportedEncodingException e) {
            throw new RuntimeException("解密失敗", e);
        }
    }

    // ===== 公共 API:不同編碼格式 =====

    /** 加密 → 十六進制字符串 (最常用,便於存儲/傳輸) */
    public static String encryptHex(String content, String password) {
        return bytesToHex(encryptBytes(content, password));
    }

    /** 解密 ← 十六進制字符串 */
    public static String decryptHex(String hex, String password) {
        return decryptBytes(hexToBytes(hex), password);
    }

    /** 加密 → Base64 字符串 (URL 安全、JSON 友好) */
    public static String encryptBase64(String content, String password) {
        return Base64.getEncoder().encodeToString(encryptBytes(content, password));
    }

    /** 解密 ← Base64 字符串 */
    public static String decryptBase64(String base64, String password) {
        return decryptBytes(Base64.getDecoder().decode(base64), password);
    }

    // ===== 編碼轉換工具 =====

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            String h = Integer.toHexString(b & 0xFF);
            if (h.length() == 1) sb.append('0');
            sb.append(h);
        }
        return sb.toString().toLowerCase();
    }

    private static byte[] hexToBytes(String hex) {
        if (hex.length() % 2 != 0) throw new IllegalArgumentException("Hex 長度必須為偶數");
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            int high = Character.digit(hex.charAt(i * 2), 16);
            int low = Character.digit(hex.charAt(i * 2 + 1), 16);
            if (high < 0 || low < 0) throw new IllegalArgumentException("非法 Hex 字符");
            bytes[i] = (byte) ((high << 4) + low);
        }
        return bytes;
    }

    // ===== 測試主方法 =====
    public static void main(String[] args) {
        String pwd = "MySecretKey123";
        String text = "敏感數據:用戶身份證 110101199001011234";

        String hex = encryptHex(text, pwd);
        System.out.println("Hex密文: " + hex);

        String dec = decryptHex(hex, pwd);
        System.out.println("解密明文: " + dec);
        System.out.println("驗證 " + (text.equals(dec) ? "通過" : "失敗"));
    }
}

使用示例


進階:遷移到 CBC/GCM 模式(生產級)


總結

本工具類提供開箱即用的 AES-ECB 加解密,代碼簡潔、異常處理統一、編碼格式豐富。理解其核心流程(密鑰派生 → Cipher 初始化 → doFinal → 編碼),即可靈活擴展至 CBC/GCM 等更安全模式,滿足合規要求。

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