← 中文资源

简体中文版本

AES-GCM 加密与篡改检测

AES/GCM/NoPadding 加密敏感字段:每次加密换 96-bit IV,密文尾部带 128-bit 认证 tag;解密端 tag 校验失败即抛 AEADBadTagException,密文被篡改立刻暴露。

阅读英文原文

实现说明

AES-GCM 加密与篡改检测的核心是类 FieldCipher。

使用要点

  • 演示输出是带标签的(ciphertext bytes:、decrypted:、tampered ->),每个操作都会留下自己的一行标注。

常见问题

运行「AES-GCM 加密与篡改检测」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 ciphertext bytes:、decrypted:、tampered -> 标签标明各步骤。

核心语句

cipher.init(Cipher.ENCRYPT_MODE, keySpec, new GCMParameterSpec(128, iv));
cipher.init(Cipher.DECRYPT_MODE, keySpec, new GCMParameterSpec(128, iv));
cipher.doFinal("card 4111-1111".getBytes(StandardCharsets.UTF_8));

代码示例

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class FieldCipher {

    public static void main(String[] args) throws Exception {
        byte[] key = new byte[32]; // AES-256:真实项目从 KMS/环境变量派生,别硬编码
        new SecureRandom().nextBytes(key);
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

        byte[] iv = new byte[12]; // GCM 标准 96-bit IV,每次加密都必须换新
        new SecureRandom().nextBytes(iv);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, new GCMParameterSpec(128, iv));
        byte[] ciphertext =
                cipher.doFinal("card 4111-1111".getBytes(StandardCharsets.UTF_8));
        System.out.println("ciphertext bytes: " + ciphertext.length); // 明文 + 16 字节 tag

        cipher.init(Cipher.DECRYPT_MODE, keySpec, new GCMParameterSpec(128, iv));
        System.out.println("decrypted: "
                + new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8));

        // 篡改一个字节:认证 tag 校验失败,解密抛 AEADBadTagException
        ciphertext[0] ^= 1;
        cipher.init(Cipher.DECRYPT_MODE, keySpec, new GCMParameterSpec(128, iv));
        try {
            cipher.doFinal(ciphertext);
        } catch (Exception e) {
            System.out.println("tampered -> " + e.getClass().getSimpleName());
        }
    }
}