Cipher AES GCM Tamper Detection

Encrypt sensitive fields with AES/GCM/NoPadding: a fresh 96-bit IV per message, a 128-bit auth tag on the ciphertext, and exceptions on tampering.

JavaSecurity Boundaries

Code

snippet
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());
        }
    }
}

Inside the snippet

Count the class FieldCipher as the entire surface area of Cipher AES GCM Tamper Detection.

Using it

The demo output is labeled (ciphertext bytes:, decrypted:, tampered ->), so the printed output reads as a trace of the operations performed.

Key statements

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));

Interactive Tools for This Topic

FAQ

What does Cipher AES GCM Tamper Detection print when run?
Run it as a complete program — the output lines carry labels such as `ciphertext bytes:`, `decrypted:`, `tampered ->`.