Java SE API

AES/GCM/NoPadding

Select authenticated encryption; enforce unique nonces and verify tags before plaintext use.

Formal Syntax & Structure

java syntaxjava
Cipher.getInstance("AES/GCM/NoPadding")

Working Example

Example Snippetjava
import java.io.*;import java.nio.charset.StandardCharsets;import java.security.*;import java.util.*;import javax.crypto.*;import javax.crypto.spec.GCMParameterSpec;import javax.net.ssl.*;public class Main {    record Envelope(byte[] nonce, byte[] ciphertext) {}    static SecretKey newKey() throws GeneralSecurityException {        KeyGenerator keys = KeyGenerator.getInstance("AES");        keys.init(128);        return keys.generateKey();    }    static Envelope seal(SecretKey key, String text, String context) throws GeneralSecurityException {        byte[] nonce = new byte[12];        new SecureRandom().nextBytes(nonce);        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");        cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce));        cipher.updateAAD(context.getBytes(StandardCharsets.UTF_8));        return new Envelope(nonce, cipher.doFinal(text.getBytes(StandardCharsets.UTF_8)));    }    static String open(SecretKey key, Envelope envelope, String context) throws GeneralSecurityException {        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");        cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, envelope.nonce()));        cipher.updateAAD(context.getBytes(StandardCharsets.UTF_8));        return new String(cipher.doFinal(envelope.ciphertext()), StandardCharsets.UTF_8);    }    public static void main(String[] args) throws Exception {        SecretKey key = newKey();        Envelope envelope = seal(key, "stock:3", "warehouse:v1");        System.out.println(open(key, envelope, "warehouse:v1"));        try {            open(key, envelope, "warehouse:v2");            throw new AssertionError("wrong context accepted");        } catch (AEADBadTagException expected) {            System.out.println("rejected");        }    }}
Java Reference