An AEADBadTagException on decrypt means AES-GCM’s authentication check failed. The bytes, the IV or the key differ from what encryption used. In hand-written Android Keystore code, two bugs usually stack up. First, the ciphertext gets stored with String(bytes). That decodes random bytes as UTF-8. Invalid sequences become replacement characters. The bytes you read back are no longer the bytes you wrote, so the tag check fails. Second, the IV is never stored. Decryption reuses cipher.iv from a shared Cipher. That holds the IV of the last value encrypted, not the one being read. After a process restart it’s null. Fixing only the first bug makes a one-value test pass. Production then fails with a second value or a cold start. The fix stores the IV and ciphertext together as Base64. Decryption reads the IV back from that stored value. Also use a new Cipher for each operation.
A token vault that throws AEADBadTagException on the first read
This code has become more common since AndroidX deprecated its crypto library. The security-crypto release notes for 1.1.0-alpha07, from April 2025, deprecate all its APIs. They point developers to platform APIs and the Android Keystore instead. That covers EncryptedSharedPreferences. So teams now write the Keystore and Cipher code themselves. Here is a typical first version. It stores a refresh token in a String-only key-value store, like SharedPreferences.
class TokenVault(private val key: SecretKey, private val prefs: SharedPreferences) {
private val cipher = Cipher.getInstance("AES/GCM/NoPadding")
fun save(name: String, token: String) {
cipher.init(Cipher.ENCRYPT_MODE, key)
val encrypted = cipher.doFinal(token.toByteArray())
prefs.edit { putString(name, String(encrypted)) }
}
fun load(name: String): String {
val encrypted = prefs.getString(name, null)!!.toByteArray()
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, cipher.iv))
return String(cipher.doFinal(encrypted))
}
}
We ran the same class on the JVM. A KeyGenerator AES-256 key stood in for the Keystore key. A plain map stood in for SharedPreferences. The first read failed straight after the save. A new vault, like the one a restarted process builds, failed with a different error.
load right after save -> javax.crypto.AEADBadTagException: Tag mismatch load after process restart -> java.lang.IllegalArgumentException: src array is null
On a device the message differs. In the AOSP Keystore cipher code, a failed Keystore tag check becomes a bare AEADBadTagException. It has no message. The real error sits in its cause. So a crash report may show only the class name.
Cause one: String(bytes) changes the ciphertext before you store it
GCM output is random-looking binary. It isn’t text in any encoding. Kotlin’s String(bytes) decodes it as UTF-8 anyway. The Android reference for java.lang.String says this decoding always replaces malformed input with the charset’s replacement string. Random bytes are full of malformed UTF-8 sequences. Each one becomes U+FFFD. That character takes three bytes when encoded again.
So toByteArray() on the stored string gives different bytes. In our run, a 31-byte ciphertext came back as 50 bytes. Another run gave 59. The last 16 bytes of GCM output are the authentication tag. The tag now covers bytes that no longer exist. So decryption fails on every read. This step can’t be undone either. The replacement character has thrown away the original bytes.
That’s why the first read fails in the same session. At that moment the shared cipher still holds the right IV.
Cause two: cipher.iv belongs to the last encryption, not the stored value
The obvious next step is Base64. Swap String(encrypted) for Base64.encode(encrypted) and decode it on load. We ran that version. A test that saves one token and reads it back passes. Then it breaks two different ways.
one token, same instance -> rt_8f2c1d9e4b7a refresh after saving access -> javax.crypto.AEADBadTagException: Tag mismatch after process restart -> java.lang.IllegalArgumentException: src array is null
GCM needs the same IV for decryption that encryption used. The vault never stores it. Instead, load() reads cipher.iv from the shared instance. Per the Cipher.getIV() reference, that returns the IV the cipher holds now. It returns null if no IV has been set yet.
Both failures follow from that. Saving the access token gives the shared cipher a new IV. Reading the refresh token then decrypts with the access token’s IV, so the tag check fails. After a restart, the new Cipher has never been initialized. getIV() returns null. The GCMParameterSpec constructor throws IllegalArgumentException when its IV array is null. Apps often read a stored token right at launch. So the crash can land on the next cold start.
A hard-coded IV won’t work with a Keystore key either. KeyGenParameterSpec.Builder says Keystore keys reject caller-provided IVs for GCM encryption by default. It recommends letting the cipher pick a random IV and reading it with getIV(). The Keystore’s own GCM code also refuses to encrypt twice with one IV. That check is in AndroidKeyStoreAuthenticatedAESCipherSpi. The IV is random per value, so it has to travel with the value.
The fix: store the IV with the ciphertext, as Base64
Read the IV after init, prepend it to the ciphertext and Base64 the whole thing. On load, split the first 12 bytes back off. The AOSP GCM cipher only accepts a 12-byte IV for Keystore keys. Each call also gets its own Cipher. Nothing then depends on what the last call left behind.
class TokenVault(private val key: SecretKey, private val prefs: SharedPreferences) {
fun save(name: String, token: String) {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, key) // the provider picks a fresh IV
val iv = cipher.iv // 12 bytes for GCM
val encrypted = cipher.doFinal(token.encodeToByteArray())
prefs.edit { putString(name, Base64.encode(iv + encrypted)) }
}
fun load(name: String): String? {
val stored = prefs.getString(name, null)?.let { Base64.decode(it) } ?: return null
val iv = stored.copyOfRange(0, IV_SIZE)
val encrypted = stored.copyOfRange(IV_SIZE, stored.size)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, iv))
return cipher.doFinal(encrypted).decodeToString()
}
private companion object {
const val TRANSFORMATION = "AES/GCM/NoPadding"
const val IV_SIZE = 12
const val TAG_BITS = 128
}
}
// The Keystore key the vault receives.
fun vaultKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(keyStore.getKey("token_vault", null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init(
KeyGenParameterSpec.Builder(
"token_vault",
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build()
)
return generator.generateKey()
}
Base64 here is kotlin.io.encoding.Base64. It compiled without an opt-in on Kotlin 2.4.20. The vault class is plain JVM code, so we ran it with the same stand-ins as before. Both earlier failures now read the right token. The provider’s IV was 12 bytes. Then we flipped one bit of a stored value. That read failed with AEADBadTagException, as it should.
refresh after saving access -> rt_8f2c1d9e4b7a after process restart -> at_31c0aa7e provider IV length: 12 tampered value -> javax.crypto.AEADBadTagException: Tag mismatch
The tampered read shows how to handle the exception in production. After the fix, an AEADBadTagException means the stored value really is bad. It may have been altered, or the key may have been replaced. Clearing the value and sending the user to sign in again is a reasonable response. Before the fix, the same exception meant your own code had damaged the data. Our earlier post on KeyPermanentlyInvalidatedException covers the other way a Keystore key stops decrypting.
How to walk an interviewer from the exception to the fix
This snippet works well in a live debugging round. The interviewer says token reads fail with AEADBadTagException. Our post on how the Android debugging round is scored explains why the second bug matters. A strong answer goes in this order.
- Say what the exception proves. GCM verifies a tag over the ciphertext. Failure means the key, IV or bytes differ from encryption time.
- Check the bytes first.
String(encrypted)decodes binary as UTF-8. Malformed sequences becomeU+FFFD, so the bytes change. Use Base64. - Check the IV next.
cipher.ivis the IV of the lastinit. It’s wrong after a second save andnullafter a restart. - Give the fix. Store the IV with the ciphertext, split it off on load and use a new
Cipherper call. - Explain why a fixed IV is wrong. Keystore keys reject caller-provided IVs by default. Reusing a GCM IV with one key is the failure that rule prevents.
- Name the test that would have caught it. Save two values, then read the first from a new vault instance.
Wrong answers that hide one bug and keep the other
- “Use Base64 and you’re done.” It fixes cause one. Our run still failed on the second token and after a restart.
- “Turn off
setRandomizedEncryptionRequiredand use a constant IV.” The IV problem goes away because every value shares one IV. TheKeyGenParameterSpec.Builderreference explains the cost. Equal plaintexts then give equal ciphertexts. That leaks information about the plaintext. - “Keep the
Cipheras a field and reuse it.” Sharing the instance is what made the wrong IV available. A new instance per call costs little and holds no leftover state. - “Catch
AEADBadTagExceptionand returnnull.” Before the fix, that turns a bug in your code into users who are silently signed out. Catch it only once the code can’t cause it. - “The Keystore key must be broken.” The key was fine in our repro. Both failures came from the code around it.