Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams
Encrypting data with javax.crypto.Cipher: AES, why ECB and unauthenticated modes are dangerous, PKCS #5 padding, AES-GCM with nonces and associated data, ChaCha20-Poly1305, generating and wrapping keys, SecureRandom, and encrypting files with cipher streams.
kvi5hnuCode Sprout team member13 min readOn this page
Signatures (article 84) prove where data came from, but anyone can read it. When information must stay confidential, such as personal data, credentials or backups, you need encryption: a transformation that only the holder of a key can undo. This article covers symmetric encryption, where the same secret key encrypts and decrypts. It is fast and is what actually protects bulk data everywhere, including inside TLS. Article 87 covers public key encryption, which mainly solves the problem of getting a symmetric key to the other side.
The Cipher class
All encryption in Java goes through javax.crypto.Cipher. You ask for a transformation, a string of the form algorithm/mode/padding:
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
byte[] ciphertext = cipher.doFinal(plaintext);
init takes one of four modes: ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE and UNWRAP_MODE (the last two encrypt and decrypt keys). After init, you can feed data piece by piece with update, which returns whatever output is ready, and you must finish with doFinal, which processes the rest, adds or checks padding and tags, and resets the cipher for the next message with the same parameters. (Exception: an AES-GCM cipher in encryption mode refuses to run again with the same key and IV, throwing IllegalStateException; call init with a fresh IV for every message.) getOutputSize(n) tells you how large an output buffer must be.
The algorithm to use is AES (Advanced Encryption Standard), with 128-, 192- or 256-bit keys. It is a block cipher: by itself, it maps one 16-byte block to another. The old DES (56-bit key) can be broken by brute force within hours and must not be used; Triple DES is deprecated too.
Modes: how blocks are chained
A block cipher needs a mode of operation to handle messages longer than one block. The mode matters as much as the algorithm.
| Mode | What it does | Verdict |
|---|---|---|
| ECB | Encrypts each block independently. | Never use. Equal plaintext blocks give equal ciphertext blocks, so patterns show through. |
| CBC | XORs each block with the previous ciphertext block; needs a random IV and padding. | Confidential but not authenticated. Vulnerable to padding-oracle attacks when errors are observable. |
| CTR | Turns AES into a stream cipher by encrypting a counter. | Confidential but malleable: flipping a ciphertext bit flips the same plaintext bit. |
| GCM | CTR encryption plus a Galois authentication tag. | Recommended. Authenticated encryption. |
Both CBC and CTR keep data secret but do not detect changes. The demo shows the danger: an attacker who knows only the format of a CTR-encrypted payment order ("Pay Bob 100 euros") can XOR one ciphertext byte so that it decrypts to "Pay Bob 900 euros", without knowing the key. Encryption without integrity is almost never what you want.
Padding
Modes like ECB and CBC work on whole blocks, so the last block must be padded. The JDK's PKCS5Padding (formally PKCS #7 for 16-byte blocks) appends n bytes each holding the value n, from 1 to 16. If the data already fills the last block, a whole block of sixteen 0x10 bytes is added, so the padding is always unambiguous. The demo shows "hello" padded with eleven 0b bytes, and that 16 bytes of input become 32 bytes of output. GCM and CTR need no padding (NoPadding), and the ciphertext has the same length as the plaintext.
Authenticated encryption with AES-GCM

GCM (Galois/Counter Mode) encrypts and computes an authentication tag in one pass. On decryption the tag is checked before any plaintext is returned; if a single bit of the ciphertext, the tag, the IV or the associated data changed, doFinal throws AEADBadTagException.
Its inputs:
- Key: an AES key of 128 or 256 bits.
- IV (nonce): 12 bytes (96 bits), passed in a
GCMParameterSpectogether with the tag length in bits (use 128). The IV does not need to be secret, but it must never repeat for the same key. A repeated IV reveals the XOR of the two plaintexts and lets an attacker forge tags. SunJCE refuses to encrypt twice with the same key and IV on oneCipherobject ("Cannot reuse iv for GCM encryption"), but it cannot catch reuse across objects or processes; that is your job. The usual approach is 12 random bytes per message fromSecureRandom. With random IVs, NIST advises at most messages per key. - Associated data (AAD): optional bytes that are authenticated but not encrypted, passed with
updateAADbefore the data. Use it to bind the ciphertext to its context: a record ID, a header, a version number. A ciphertext moved to another record then fails to decrypt.
The result is ciphertext of the same length as the plaintext, followed by the 16-byte tag. A self-contained message is usually stored as IV || ciphertext || tag:
static byte[] encrypt(SecretKey key, byte[] plaintext, byte[] aad) throws GeneralSecurityException {
byte[] iv = new byte[12];
RANDOM.nextBytes(iv);
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
c.updateAAD(aad);
byte[] out = Arrays.copyOf(iv, 12 + c.getOutputSize(plaintext.length));
c.doFinal(plaintext, 0, plaintext.length, out, 12);
return out;
}
static byte[] decrypt(SecretKey key, byte[] message, byte[] aad) throws GeneralSecurityException {
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, message, 0, 12));
c.updateAAD(aad);
return c.doFinal(message, 12, message.length - 12);
}
The JDK also offers ChaCha20-Poly1305 (Java 11), an authenticated cipher with the same interface (a 256-bit key, a 12-byte nonce in an IvParameterSpec). It is fast in software on processors without AES instructions and is widely used in TLS and on mobile devices.
Keys
Generating keys
A key must be unpredictable. Use a KeyGenerator:
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256); // key size; uses a default SecureRandom
SecretKey key = kg.generateKey();
If you already have raw key bytes (from a key store, a key exchange, or a KDF), wrap them in a SecretKeySpec: new SecretKeySpec(bytes, "AES"). To derive a key from a password, run PBKDF2 (article 83) with a random salt and store the salt next to the ciphertext; for other secret material use HKDF through the KDF API.
SecureRandom
Never use java.util.Random or Math.random for keys, IVs or salts. Their output is predictable from a few observed values, and seeds from the clock are easy to guess. java.security.SecureRandom is designed for cryptography:
new SecureRandom()picks the platform's preferred implementation (on Linux and macOS,NativePRNG, which reads from the operating system; elsewhere theDRBGadded in Java 9). It seeds itself from the OS. Just create one and use it.SecureRandom.getInstanceStrong()returns the strongest configured algorithm, which on some systems may block while waiting for entropy. Prefer the default for keys and nonces in servers.setSeedadds to the seed of most implementations rather than replacing it. Gathering your own randomness from keystrokes or timing is unnecessary today; operating systems collect it from hardware.
Storing and wrapping keys
A key is as sensitive as the data it protects. Options for keeping it:
- a PKCS #12
KeyStoreprotected by a password (setEntrywith aKeyStore.SecretKeyEntry); - a key management service or hardware security module, which never reveals the key;
- key wrapping: encrypting one key with another key-encryption key (KEK). Use
Cipher.WRAP_MODE/UNWRAP_MODEwith the AES Key Wrap algorithmAES/KW/NoPadding(Java 17, RFC 3394), which is designed for this; a 256-bit key wraps into 40 bytes. This is the basis of envelope encryption: data is encrypted with a per-file data key, and the data key is stored wrapped by a master key.
Do not serialize keys with ObjectOutputStream, as older examples do. Store key.getEncoded() in a protected place, or better, use a key store.
Cipher streams
CipherOutputStream and CipherInputStream wrap ordinary streams and call update and doFinal for you:
try (OutputStream raw = Files.newOutputStream(path)) {
raw.write(iv); // IV first, unencrypted
try (var out = new CipherOutputStream(raw, cipher)) {
out.write(data);
} // close() runs doFinal and writes the tag
}
Closing the CipherOutputStream is essential: only close() calls doFinal, which writes the final block and the GCM tag. (flush() does not.) When reading, a failed tag check appears as an IOException whose cause is the AEADBadTagException.
Be aware that GCM decryption cannot release any plaintext before it has checked the tag at the very end, so the JDK's GCM implementation buffers the whole ciphertext while decrypting. That is fine for files of a few megabytes, but for large files, split the data into chunks (for example 64 KiB), each encrypted as its own GCM message with its own IV derived from a counter, and authenticate the chunk number and a "last chunk" flag as AAD so that chunks cannot be reordered, dropped or truncated.
The program
The first sections use a fixed key and IV so that the printed bytes are repeatable; the later ones use fresh random keys and nonces, as real code must, and print only facts that do not depend on the random values. The program shows ECB's pattern leak and the padding rule, a bit-flipping attack on unauthenticated CTR, AES-GCM with associated data (including the reuse check and two forgery attempts), the recommended encrypt/decrypt pair, ChaCha20-Poly1305, encrypting a file through cipher streams and detecting a one-bit change, AES key wrapping, and a key derived from a password.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Solution {
static final HexFormat HEX = HexFormat.of();
static final SecureRandom RANDOM = new SecureRandom();
static byte[] utf8(String s) { return s.getBytes(StandardCharsets.UTF_8); }
static String text(byte[] b) { return new String(b, StandardCharsets.UTF_8); }
/** Hex, with a space between 16-byte blocks. */
static String blocks(byte[] b) {
var sb = new StringBuilder();
for (int i = 0; i < b.length; i += 16) {
if (i > 0) sb.append(' ');
sb.append(HEX.formatHex(b, i, Math.min(b.length, i + 16)));
}
return sb.toString();
}
// ------------------------------------------------------------- the recommended pattern
static final int IV_BYTES = 12, TAG_BITS = 128;
/** Returns IV || ciphertext || tag. */
static byte[] encrypt(SecretKey key, byte[] plaintext, byte[] aad) throws GeneralSecurityException {
byte[] iv = new byte[IV_BYTES];
RANDOM.nextBytes(iv); // a fresh nonce for every message
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
c.updateAAD(aad);
byte[] out = Arrays.copyOf(iv, IV_BYTES + c.getOutputSize(plaintext.length));
c.doFinal(plaintext, 0, plaintext.length, out, IV_BYTES);
return out;
}
static byte[] decrypt(SecretKey key, byte[] message, byte[] aad) throws GeneralSecurityException {
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, message, 0, IV_BYTES));
c.updateAAD(aad);
return c.doFinal(message, IV_BYTES, message.length - IV_BYTES);
}
public static void main(String[] args) throws Exception {
// A fixed key and IV make the first sections repeatable. Real keys come from KeyGenerator.
SecretKey fixed = new SecretKeySpec(HEX.parseHex("000102030405060708090a0b0c0d0e0f"), "AES");
byte[] fixedIv = HEX.parseHex("cafebabefacedbaddecaf888");
System.out.println("== Cipher.getInstance(\"AES\") means AES/ECB/PKCS5Padding ==");
Cipher ecb = Cipher.getInstance("AES");
ecb.init(Cipher.ENCRYPT_MODE, fixed);
byte[] twoSameBlocks = utf8("ATTACK AT DAWN!!ATTACK AT DAWN!!");
System.out.println("plaintext : " + blocks(twoSameBlocks));
System.out.println("ciphertext: " + blocks(ecb.doFinal(twoSameBlocks)));
System.out.println("equal plaintext blocks give equal ciphertext blocks -> patterns leak");
System.out.println("\n== PKCS #5 padding: output length for input length n ==");
var sizes = new StringBuilder();
for (int n : new int[] {0, 1, 15, 16, 17, 31, 32}) sizes.append(n).append("->").append(ecb.doFinal(new byte[n]).length).append(" ");
System.out.println(sizes.toString().strip());
Cipher ecbDec = Cipher.getInstance("AES/ECB/NoPadding");
ecbDec.init(Cipher.DECRYPT_MODE, fixed);
System.out.println("padding added to \"hello\": " + HEX.formatHex(ecbDec.doFinal(ecb.doFinal(utf8("hello"))), 5, 16));
System.out.println("\n== Encryption without integrity: flipping bits in CTR mode ==");
Cipher ctr = Cipher.getInstance("AES/CTR/NoPadding");
ctr.init(Cipher.ENCRYPT_MODE, fixed, new IvParameterSpec(HEX.parseHex("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")));
byte[] order = ctr.doFinal(utf8("Pay Bob 100 euros"));
order[8] ^= '1' ^ '9'; // attacker knows the format, not the key
ctr.init(Cipher.DECRYPT_MODE, fixed, new IvParameterSpec(HEX.parseHex("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")));
System.out.println("decrypts without complaint to: " + text(ctr.doFinal(order)));
System.out.println("\n== AES-GCM: authenticated encryption ==");
Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding");
gcm.init(Cipher.ENCRYPT_MODE, fixed, new GCMParameterSpec(128, fixedIv));
byte[] aad = utf8("order-id=4711");
gcm.updateAAD(aad);
byte[] sealed = gcm.doFinal(utf8("Pay Bob 100 euros"));
System.out.println("17 bytes in -> " + sealed.length + " out (ciphertext + 16-byte tag)");
System.out.println("ciphertext: " + HEX.formatHex(sealed, 0, 17));
System.out.println("tag: " + HEX.formatHex(sealed, 17, sealed.length));
try {
gcm.init(Cipher.ENCRYPT_MODE, fixed, new GCMParameterSpec(128, fixedIv));
} catch (InvalidAlgorithmParameterException e) {
System.out.println("same key + IV again: " + e.getMessage());
}
gcm.init(Cipher.DECRYPT_MODE, fixed, new GCMParameterSpec(128, fixedIv));
gcm.updateAAD(aad);
System.out.println("decrypted: " + text(gcm.doFinal(sealed)));
byte[] forged = sealed.clone();
forged[8] ^= '1' ^ '9';
try {
gcm.init(Cipher.DECRYPT_MODE, fixed, new GCMParameterSpec(128, fixedIv));
gcm.updateAAD(aad);
gcm.doFinal(forged);
} catch (AEADBadTagException e) {
System.out.println("bit flip: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
try {
gcm.init(Cipher.DECRYPT_MODE, fixed, new GCMParameterSpec(128, fixedIv));
gcm.updateAAD(utf8("order-id=4712"));
gcm.doFinal(sealed);
} catch (AEADBadTagException e) {
System.out.println("other AAD: " + e.getClass().getSimpleName());
}
System.out.println("\n== The recommended pattern: random key, random IV per message ==");
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(256);
SecretKey key = kg.generateKey();
byte[] m1 = encrypt(key, utf8("same message"), aad);
byte[] m2 = encrypt(key, utf8("same message"), aad);
System.out.println("key bits: " + key.getEncoded().length * 8 + ", message length: " + m1.length
+ " = 12 IV + 12 data + 16 tag");
System.out.println("encrypting twice gives different bytes: " + !Arrays.equals(m1, m2));
System.out.println("round trip: " + text(decrypt(key, m1, aad)) + " / " + text(decrypt(key, m2, aad)));
System.out.println("\n== ChaCha20-Poly1305, the other AEAD cipher in the JDK ==");
SecretKey chachaKey = KeyGenerator.getInstance("ChaCha20").generateKey();
byte[] nonce = new byte[12];
RANDOM.nextBytes(nonce);
Cipher chacha = Cipher.getInstance("ChaCha20-Poly1305");
chacha.init(Cipher.ENCRYPT_MODE, chachaKey, new IvParameterSpec(nonce));
byte[] cc = chacha.doFinal(utf8("Pay Bob 100 euros"));
chacha.init(Cipher.DECRYPT_MODE, chachaKey, new IvParameterSpec(nonce));
System.out.println(cc.length + " bytes, decrypts to: " + text(chacha.doFinal(cc)));
System.out.println("\n== Streams: CipherOutputStream / CipherInputStream ==");
Path file = Files.createTempFile("secret", ".bin");
try {
byte[] iv = new byte[IV_BYTES];
RANDOM.nextBytes(iv);
Cipher enc = Cipher.getInstance("AES/GCM/NoPadding");
enc.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, iv));
try (OutputStream raw = Files.newOutputStream(file)) {
raw.write(iv); // IV in the clear, first
try (var out = new CipherOutputStream(raw, enc)) { // close() calls doFinal: writes the tag
for (int i = 1; i <= 1000; i++) out.write(utf8("line " + i + "\n"));
}
}
System.out.println("file size: " + Files.size(file) + " bytes");
try (InputStream raw = Files.newInputStream(file)) {
byte[] readIv = raw.readNBytes(IV_BYTES);
Cipher dec = Cipher.getInstance("AES/GCM/NoPadding");
dec.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, readIv));
try (var in = new BufferedReader(new InputStreamReader(new CipherInputStream(raw, dec), StandardCharsets.UTF_8))) {
List<String> lines = in.lines().toList();
System.out.println("read back " + lines.size() + " lines, last: " + lines.getLast());
}
}
byte[] bytes = Files.readAllBytes(file);
bytes[100] ^= 1;
Files.write(file, bytes);
try (InputStream raw = Files.newInputStream(file)) {
Cipher dec = Cipher.getInstance("AES/GCM/NoPadding");
dec.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(TAG_BITS, raw.readNBytes(IV_BYTES)));
new CipherInputStream(raw, dec).readAllBytes();
} catch (IOException e) {
System.out.println("tampered file: " + e.getClass().getSimpleName() + " caused by "
+ e.getCause().getClass().getSimpleName());
}
} finally {
Files.delete(file);
}
System.out.println("\n== Wrapping a key with another key (AES Key Wrap) ==");
SecretKey kek = kg.generateKey(); // key-encryption key
Cipher kw = Cipher.getInstance("AES/KW/NoPadding");
kw.init(Cipher.WRAP_MODE, kek);
byte[] wrapped = kw.wrap(key);
kw.init(Cipher.UNWRAP_MODE, kek);
Key unwrapped = kw.unwrap(wrapped, "AES", Cipher.SECRET_KEY);
System.out.println("wrapped 32-byte key into " + wrapped.length + " bytes; unwrapped equals original: "
+ Arrays.equals(unwrapped.getEncoded(), key.getEncoded()));
System.out.println("\n== A key from a password (PBKDF2, see article 83) ==");
byte[] salt = HEX.parseHex("6b1f0c55d6a2e03c94f1b2a7c3d8e941");
var spec = new PBEKeySpec("correct horse battery staple".toCharArray(), salt, 600_000, 256);
byte[] derived = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
spec.clearPassword();
SecretKey fromPassword = new SecretKeySpec(derived, "AES");
System.out.println("derived AES key: " + HEX.formatHex(fromPassword.getEncoded()).substring(0, 16) + "... ("
+ derived.length * 8 + " bits)");
System.out.println("block size of AES: " + Cipher.getInstance("AES/GCM/NoPadding").getBlockSize() + " bytes");
}
}
== Cipher.getInstance("AES") means AES/ECB/PKCS5Padding ==
plaintext : 41545441434b204154204441574e2121 41545441434b204154204441574e2121
ciphertext: 8a21cef935d8587bea999da471a91c41 8a21cef935d8587bea999da471a91c41 954f64f2e4e86e9eee82d20216684899
equal plaintext blocks give equal ciphertext blocks -> patterns leak
== PKCS #5 padding: output length for input length n ==
0->16 1->16 15->16 16->32 17->32 31->32 32->48
padding added to "hello": 0b0b0b0b0b0b0b0b0b0b0b
== Encryption without integrity: flipping bits in CTR mode ==
decrypts without complaint to: Pay Bob 900 euros
== AES-GCM: authenticated encryption ==
17 bytes in -> 33 out (ciphertext + 16-byte tag)
ciphertext: d918be96c798e3219b20f9a8388fd288f5
tag: f14248a236fc11e2bee850c8f1761d22
same key + IV again: Cannot reuse iv for GCM encryption
decrypted: Pay Bob 100 euros
bit flip: AEADBadTagException: Tag mismatch
other AAD: AEADBadTagException
== The recommended pattern: random key, random IV per message ==
key bits: 256, message length: 40 = 12 IV + 12 data + 16 tag
encrypting twice gives different bytes: true
round trip: same message / same message
== ChaCha20-Poly1305, the other AEAD cipher in the JDK ==
33 bytes, decrypts to: Pay Bob 100 euros
== Streams: CipherOutputStream / CipherInputStream ==
file size: 8921 bytes
read back 1000 lines, last: line 1000
tampered file: IOException caused by AEADBadTagException
== Wrapping a key with another key (AES Key Wrap) ==
wrapped 32-byte key into 40 bytes; unwrapped equals original: true
== A key from a password (PBKDF2, see article 83) ==
derived AES key: b40d0753e0480029... (256 bits)
block size of AES: 16 bytes
Points to notice:
- The ECB ciphertext has three blocks: two identical ones for the two identical plaintext blocks, and a full padding block, because 32 bytes is an exact multiple of 16.
- In GCM, 17 bytes of plaintext became 17 bytes of ciphertext plus a 16-byte tag. With the 12-byte IV, a self-contained message costs 28 bytes of overhead.
- The same flip that turned "100" into "900" under CTR is caught by GCM, which uses CTR internally but adds the tag.
Common questions
How do I encrypt a string and store it as text?
Encrypt the UTF-8 bytes with AES-GCM, prepend the IV, and Base64-encode IV || ciphertext || tag. To decrypt, Base64-decode, split off the 12-byte IV, and decrypt the rest. The demo's encrypt and decrypt methods show the full pattern.
Can I reuse an IV with the same key? Never with GCM: two messages with the same key and IV leak the XOR of their plaintexts and allow forgeries. The JDK even refuses to re-initialize a GCM cipher for encryption with the same key and IV. Use a fresh random 12-byte IV for every message, or a counter that never repeats.
How many messages can I encrypt with one key? With random 96-bit IVs, the NIST limit is 2^32 messages per key, to keep the IV collision risk negligible. Rotate keys well before that, or use counter-based IVs.
Where should the encryption key live? Not in source code or next to the data. Use a key management service (AWS KMS, Google Cloud KMS, Azure Key Vault, HashiCorp Vault), a hardware security module, or at least a PKCS #12 key store with a password from the environment. Many systems use envelope encryption: data keys encrypted by a master key in the KMS.
AES-128 or AES-256? Both are secure against all known classical attacks. AES-256 adds a margin against future quantum attacks (Grover's algorithm halves the effective key length) and is required by some policies. The performance difference is small.
Why does decryption fail with AEADBadTagException?
Something differs from encryption: the key, the IV, the associated data, the tag length, or the ciphertext itself (including truncation or Base64 damage). GCM can't say which, by design.
API reference
| Class / method | Purpose |
|---|---|
Cipher.getInstance("AES/GCM/NoPadding") | Get a cipher for a transformation. Other useful ones: ChaCha20-Poly1305, AES/KW/NoPadding, AES/CBC/PKCS5Padding (legacy). |
init(mode, key [, params] [, random]) | ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE, UNWRAP_MODE. |
updateAAD(bytes) | Associated data for AEAD modes, before any update. |
update(...), doFinal(...) | Process data; doFinal finishes the message and resets. |
getOutputSize(n), getBlockSize(), getIV(), getParameters() | Sizes and parameters. |
wrap(key), unwrap(bytes, alg, type) | Encrypt and decrypt keys. |
GCMParameterSpec(tagBits, iv), IvParameterSpec(iv) | IV and tag length. |
AEADBadTagException | Authentication failed; no plaintext is returned. |
KeyGenerator.getInstance("AES"), init(bits), generateKey() | Random secret keys. |
SecretKeySpec(bytes, "AES") | A key from raw bytes. |
SecureRandom, nextBytes, getInstanceStrong() | Cryptographic randomness. |
CipherOutputStream, CipherInputStream | Encrypt or decrypt while writing or reading; close() finishes. |
Summary
- Symmetric ciphers use one secret key for both directions. Use AES with 128- or 256-bit keys; DES and Triple DES are obsolete.
- Always give the full transformation.
"AES"alone means ECB, which leaks patterns. - Use authenticated encryption:
AES/GCM/NoPaddingwith a 12-byte random IV per message and a 128-bit tag, orChaCha20-Poly1305. Never reuse an IV with the same key. StoreIV || ciphertext || tagand bind context with AAD. - CBC and CTR alone do not detect tampering, and CTR ciphertexts can be edited bit by bit.
- Generate keys with
KeyGeneratorand randomness withSecureRandom. Derive keys from passwords with PBKDF2. Protect keys in a key store, KMS or by wrapping withAES/KW/NoPadding. - Cipher streams handle
update/doFinal; always close them. For very large data, encrypt in authenticated chunks.
Practice Questions
1. A colleague encrypts database fields with Cipher.getInstance("AES") and a fixed key. What is wrong, and what should the code look like?
"AES" means ECB mode: identical field values give identical ciphertexts (so an observer can tell which users share a value), patterns inside longer values show through, and nothing detects tampering. Use AES/GCM/NoPadding with a fresh 12-byte random IV for every encryption, store the IV with the ciphertext and tag, and pass something like the table name and row ID as AAD so ciphertexts cannot be moved between rows.
2. Why is AES-GCM with a counter-based IV safe across server restarts only if you take care, and what is the simplest safe choice?
GCM breaks badly if the same key and IV are ever used twice. A counter kept in memory restarts at zero after a reboot, and several servers sharing a key would produce the same counter values. Unless the counter is persisted reliably and partitioned per server, IVs repeat. The simplest safe choice is a random 12-byte IV from SecureRandom for every message, while staying well below about messages per key, then rotating keys.
3. Decryption of a CBC message with a wrong key sometimes throws BadPaddingException and sometimes returns garbage. Why?
CBC decryption with the wrong key produces random-looking bytes. The cipher then checks the last bytes for valid PKCS #5 padding. Most of the time they are not valid padding and you get BadPaddingException; but about 1 time in 256 the final byte happens to be 01 (valid one-byte padding), and you get garbage with no error. Padding is not an integrity check, which is another reason to use an authenticated mode, where a wrong key always fails with AEADBadTagException.
4. You encrypt a file with a CipherOutputStream and GCM, but the decryption always fails with a tag mismatch. The writer calls out.flush() at the end. What is missing?
The CipherOutputStream was never closed. flush() does not finish the cipher; only close() calls doFinal, which writes the last part of the ciphertext and the 16-byte tag. Without it the file is truncated and authentication fails. Use try-with-resources around the cipher stream.
5. What is envelope encryption, and which JDK algorithm fits the "envelope" part?
Each piece of data (a file, a record set) is encrypted with its own random data key, for example with AES-GCM. The data key is then encrypted ("wrapped") with a long-term key-encryption key, often kept in a KMS or HSM, and stored next to the data. Rotating the master key only requires rewrapping small data keys, not re-encrypting all data. In the JDK, wrap keys with Cipher.getInstance("AES/KW/NoPadding") in WRAP_MODE/UNWRAP_MODE, or with AES-GCM.
Previous: Certificates in Java: keytool, Certificate Chains and Signing JAR Files
Next: Public Key Encryption in Java: RSA, Hybrid Encryption and ML-KEM
Related reading

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.