Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

Review this code and explain what is wrong:

Java
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(FIXED_IV));
byte[] out = c.doFinal(data);

Cipher.getInstance("AES") does not choose a safe mode; it falls back to the provider default, which for the JDK's SunJCE is AES/ECB/PKCS5Padding. ECB leaks patterns, is not authenticated and takes no IV, so passing an IvParameterSpec makes init fail, and in any mode that does use an IV, a fixed IV breaks security. The fix is AES/GCM/NoPadding with a fresh random 12-byte IV from SecureRandom for every message and a 128-bit tag through GCMParameterSpec, never reusing an IV with the same key, storing the IV with the ciphertext, and ideally using a library such as Google Tink that makes these choices for us.

Why this question is asked

This three-line snippet is a favourite in code reviews and interviews because almost everything in it looks reasonable and almost everything is wrong. It compiles, it may even run, and a test that encrypts and decrypts one value passes. The problems only show up when an attacker looks at many ciphertexts or changes one. In this answer, we will recap what modes and IVs are, go through the snippet line by line to see what actually happens, write the corrected version with AES-GCM, see why IV reuse is so dangerous in GCM, and look at how to store the result and avoid writing this code at all.

1A Quick Recap of Modes and IVs

AES is a block cipher: it encrypts exactly 16 bytes at a time. To encrypt longer data we need a mode of operation, which defines how blocks are chained. ECB (electronic codebook) encrypts each block separately. CBC chains each block with the previous one. GCM (Galois/Counter Mode) turns AES into a stream of key material and also computes an authentication tag over the result.

An IV (initialisation vector, called a nonce in GCM) is a value that makes each encryption unique even when the key and plaintext are the same. It is not secret, but in most modes it must never repeat for the same key, and in CBC it must also be unpredictable. The transformation string given to Cipher.getInstance names all three parts: algorithm, mode and padding, for example AES/GCM/NoPadding.

2What the Snippet Actually Does

The first line asks only for "AES". The JCA then uses the provider's default mode and padding. With the JDK's SunJCE provider that is AES/ECB/PKCS5Padding, and other providers may choose differently, which already makes the code's behaviour depend on the environment.

Java
Cipher c = Cipher.getInstance("AES"); // SunJCE: AES/ECB/PKCS5Padding
c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(FIXED_IV));
// java.security.InvalidAlgorithmParameterException: ECB mode cannot use IV
byte[] out = c.doFinal(data); // never reached with SunJCE

With SunJCE, the second line fails, because ECB has no IV and the provider refuses one. So the code is either broken outright, or, if someone "fixes" it by removing the IV, it encrypts in ECB. Either way the author's intent, a mode with an IV, did not happen.

3Why ECB and a Fixed IV Are Both Insecure

ECB encrypts identical 16-byte blocks to identical ciphertext blocks. So patterns in the data survive encryption: two customers with the same account number produce the same ciphertext, and structured data like images or fixed-format records stays recognisable. ECB also has no integrity, so an attacker can swap, repeat or remove blocks and the decryption still succeeds with altered content.

Now suppose the author had written AES/CBC/PKCS5Padding with FIXED_IV. Encryption would work, but every message starting with the same bytes would produce the same first ciphertext block, which again leaks equality. CBC also has no authentication, which allows padding oracle attacks when the service reports decryption errors differently. In GCM the fixed IV is worse still, as we will see, because it can reveal plaintext and allow forgery.

Java
byte[] key16 = new byte[16]; // all-zero key, demo only
Cipher ecb = Cipher.getInstance("AES/ECB/PKCS5Padding");
ecb.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key16, "AES"));
byte[] two = ecb.doFinal("ACCOUNT=12345678ACCOUNT=12345678".getBytes(StandardCharsets.US_ASCII));
System.out.println(Arrays.equals(Arrays.copyOfRange(two, 0, 16),
Arrays.copyOfRange(two, 16, 32))); // true: same block, same ciphertext

4The Fix: AES-GCM With a Random IV per Message

The corrected code asks for AES/GCM/NoPadding explicitly. GCM is a stream mode, so it needs no padding. For every message we generate a new 12-byte IV with SecureRandom; 12 bytes is the size GCM is designed for. GCMParameterSpec takes the tag length in bits, and 128 is the standard choice. The output is the ciphertext followed by the 16-byte tag.

Java
private static final SecureRandom RNG = new SecureRandom();
static byte[] encrypt(SecretKey key, byte[] plain, byte[] aad) throws GeneralSecurityException {
byte[] iv = new byte[12];
RNG.nextBytes(iv); // fresh for every message
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
c.updateAAD(aad); // optional context, e.g. "customer:42"
byte[] ct = c.doFinal(plain); // plain.length + 16
return ByteBuffer.allocate(12 + ct.length).put(iv).put(ct).array(); // iv || ciphertext || tag
}
static byte[] decrypt(SecretKey key, byte[] blob, byte[] aad) throws GeneralSecurityException {
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, blob, 0, 12));
c.updateAAD(aad);
return c.doFinal(blob, 12, blob.length - 12); // AEADBadTagException if anything changed
}
Step throughEncrypting one message with AES-GCM
  1. Generate 12-byte IVSecureRandom, new for every message
  2. Init AES/GCM/NoPaddingGCMParameterSpec(128, iv)
  3. Add associated datarecord id or context, optional
  4. doFinalciphertext plus 16-byte tag
  5. Store iv || ciphertext || tagwith a key id if keys rotate

5 steps in order. Play them, or step through them one at a time.

Notice the decrypt side: if a single bit of the ciphertext, the IV or the associated data was altered, doFinal throws AEADBadTagException instead of returning garbage. That is the authentication ECB and CBC lack. The associated data (AAD) is not encrypted but is covered by the tag, so binding a ciphertext to its record id stops an attacker from moving it to another record.

5Never Reuse an IV With the Same Key

GCM works by encrypting a counter that starts from the IV and XORing the result with the plaintext. If two messages use the same key and IV, they are XORed with the same key stream, so XORing the two ciphertexts gives the XOR of the two plaintexts, and knowing one message reveals the other. Worse, IV reuse leaks information about the authentication key, which lets an attacker forge valid tags for messages of their choice.

The JDK protects us a little: after doFinal, a GCM Cipher in encrypt mode refuses to encrypt again until it is initialised with a new IV, and rejects an init with the key and IV it just used. But it cannot know about IVs across processes or restarts, so random IVs per message are the practical rule. With random 96-bit IVs, the usual guidance is to stay well below about 2^32 messages per key, after which we rotate the key.

6Storing the Result and Avoiding the Problem

The IV is not secret, so we store it with the ciphertext; the common layout is IV, then ciphertext, then tag, often prefixed with a version byte and key id, and Base64 encoded if it must go into text. Without the IV the data can never be decrypted.

Better still, we avoid writing this code. Google Tink offers an Aead interface with encrypt(plaintext, associatedData) and decrypt, chooses AES-GCM with random IVs, adds a key id prefix and supports key rotation. The less low-level cryptography each team writes, the fewer of these reviews we need.

Java
// With Tink (check the current API version)
AeadConfig.register();
KeysetHandle handle = KeysetHandle.generateNew(PredefinedAeadParameters.AES256_GCM);
Aead aead = handle.getPrimitive(RegistryConfiguration.get(), Aead.class);
byte[] ct = aead.encrypt(plain, "customer:42".getBytes(StandardCharsets.UTF_8));
byte[] pt = aead.decrypt(ct, "customer:42".getBytes(StandardCharsets.UTF_8)); // original bytes

7Follow-up questions

Why not AES/CBC/PKCS5Padding with a random IV?

With a random IV, CBC is confidential, but it still has no integrity. An attacker can modify ciphertext and, if the service reveals padding errors, decrypt it byte by byte with a padding oracle attack. We would have to add an HMAC over the IV and ciphertext ourselves; GCM gives us that built in.

Is a counter better than a random IV for GCM?

A counter guarantees uniqueness as long as it is never reset and never shared between instances, which is hard to guarantee across restarts and many pods. Random 12-byte IVs avoid that coordination at the cost of a limit on messages per key, which is fine for most applications.

8Conclusion

In this answer, we saw that Cipher.getInstance("AES") falls back to the provider default, AES/ECB/PKCS5Padding in SunJCE, which leaks patterns, is not authenticated and refuses an IV, while a fixed IV breaks security in modes that use one. The fix is AES/GCM/NoPadding with a random 12-byte IV per message from SecureRandom and a 128-bit tag through GCMParameterSpec, never reusing an IV with the same key, storing the IV with the ciphertext, and preferring a library such as Google Tink.

What to say in the interviewAbout 90 seconds aloud

Open with

There are three problems. First, Cipher.getInstance with just AES does not pick a safe mode; the provider default is used, which for SunJCE is AES/ECB/PKCS5Padding. ECB encrypts identical 16-byte blocks to identical ciphertext, so patterns leak, and it has no integrity, so blocks can be swapped or changed without detection.

Then, if they want more

Second, ECB has no IV at all, so with SunJCE the init call actually throws InvalidAlgorithmParameterException; the code is broken, and if someone removes the IV to make it work, it silently uses ECB. Third, the IV is fixed.

In any mode that uses an IV, a constant one makes equal messages produce equal ciphertext, and in GCM reusing an IV with the same key is catastrophic: the XOR of two ciphertexts gives the XOR of the plaintexts, and the authentication key leaks, so tags can be forged.

My fix is to name the transformation explicitly, AES/GCM/NoPadding, generate a fresh 12-byte IV with SecureRandom for every message, pass GCMParameterSpec with a 128-bit tag, and optionally bind the record id as associated data.

I store the IV in front of the ciphertext and tag, plus a key id if keys rotate, and on decryption an AEADBadTagException means the data was tampered with. In real code I would rather use Google Tink's Aead interface, which makes all these choices correctly and handles key rotation, so teams do not write low-level cipher code at all.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Review this code and explain what is wrong:": https://scrivio-interview-library.netlify.app/spring-boot/secrets-and-crypto/3e0dfbaa63/