Java AES-GCM 模式认证加密指南

AES-GCM(Galois/Counter Mode)是一种认证加密算法,同时提供数据保密性完整性验证。其核心优势在于:

  1. 单次处理完成加密和认证
  2. 支持关联数据(AAD)的认证
  3. 高效并行计算
数学基础

认证标签生成依赖 GHASH 函数:
$$ \text{GHASH}(H, X) = X_1 \cdot H^{m} \oplus X_2 \cdot H^{m-1} \oplus \cdots \oplus X_m \cdot H $$
其中 $H$ 是 AES 加密零块得到的密钥,$X$ 为输入数据块。


Java 实现步骤

1. 密钥生成
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // 选择 128/192/256 位密钥
SecretKey secretKey = keyGen.generateKey();

2. 加密流程
// 初始化加密器
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
byte[] iv = new byte[12]; // 推荐 12 字节 IV
SecureRandom.getInstanceStrong().nextBytes(iv);
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv); // 128 位认证标签

cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmSpec);

// 添加关联数据 (AAD)
cipher.updateAAD("Metadata".getBytes());

// 执行加密
byte[] cipherText = cipher.doFinal(plainText.getBytes());

3. 解密与认证
cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmSpec);
cipher.updateAAD("Metadata".getBytes()); // 必须与加密时一致

try {
    byte[] decryptedText = cipher.doFinal(cipherText);
    // 认证通过才会执行此处
} catch (AEADBadTagException ex) {
    // 认证失败(数据篡改或密钥错误)
}


关键注意事项

  1. IV 管理

    • 每次加密必须使用唯一随机 IV
    • 存储时需将 IV 与密文一起保存(通常前置)
  2. 认证标签

    • Java 自动处理 128 位标签
    • 解密失败抛出 AEADBadTagException
  3. 关联数据 (AAD)

    • 用于认证未加密的元数据
    • 加解密必须使用相同 AAD
  4. 安全实践

// 使用强随机源
SecureRandom secureRandom = SecureRandom.getInstanceStrong();

// 密钥存储建议
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null);
keyStore.setEntry("aesKey", new KeyStore.SecretKeyEntry(secretKey), 
    new KeyStore.PasswordProtection("password".toCharArray()));


典型应用场景

  • HTTPS 数据传输
  • 数据库字段加密
  • 数字版权管理(DRM)
  • 硬件安全模块(HSM)通信

性能提示:GCM 模式在支持 AES-NI 指令集的 CPU 上性能优异,较 CBC 模式提升约 5 倍吞吐量。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐