{"id":911,"date":"2026-10-27T13:52:00","date_gmt":"2026-10-27T12:52:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=911"},"modified":"2026-10-26T18:28:33","modified_gmt":"2026-10-26T17:28:33","slug":"aeadbadtagexception-android-keystore-aes-gcm","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/aeadbadtagexception-android-keystore-aes-gcm\/","title":{"rendered":"AEADBadTagException When Decrypting a Saved Token With Android Keystore AES-GCM"},"content":{"rendered":"<p>An <code>AEADBadTagException<\/code> on decrypt means AES-GCM&#8217;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 <code>String(bytes)<\/code>. 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 <code>cipher.iv<\/code> from a shared <code>Cipher<\/code>. That holds the IV of the last value encrypted, not the one being read. After a process restart it&#8217;s <code>null<\/code>. 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 <code>Cipher<\/code> for each operation.<\/p>\n\n<h2>A token vault that throws AEADBadTagException on the first read<\/h2>\n\n<p>This code has become more common since AndroidX deprecated its crypto library. The <a href=\"https:\/\/developer.android.com\/jetpack\/androidx\/releases\/security\" target=\"_blank\" rel=\"noopener\">security-crypto release notes<\/a> 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 <code>EncryptedSharedPreferences<\/code>. So teams now write the Keystore and <code>Cipher<\/code> code themselves. Here is a typical first version. It stores a refresh token in a String-only key-value store, like <code>SharedPreferences<\/code>.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class TokenVault(private val key: SecretKey, private val prefs: SharedPreferences) {\n    private val cipher = Cipher.getInstance(\"AES\/GCM\/NoPadding\")\n\n    fun save(name: String, token: String) {\n        cipher.init(Cipher.ENCRYPT_MODE, key)\n        val encrypted = cipher.doFinal(token.toByteArray())\n        prefs.edit { putString(name, String(encrypted)) }\n    }\n\n    fun load(name: String): String {\n        val encrypted = prefs.getString(name, null)!!.toByteArray()\n        cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, cipher.iv))\n        return String(cipher.doFinal(encrypted))\n    }\n}<\/pre>\n\n\n<p>We ran the same class on the JVM. A <code>KeyGenerator<\/code> AES-256 key stood in for the Keystore key. A plain map stood in for <code>SharedPreferences<\/code>. The first read failed straight after the save. A new vault, like the one a restarted process builds, failed with a different error.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">load right after save -> javax.crypto.AEADBadTagException: Tag mismatch\nload after process restart -> java.lang.IllegalArgumentException: src array is null<\/pre>\n\n\n<p>On a device the message differs. In the <a href=\"https:\/\/android.googlesource.com\/platform\/frameworks\/base\/+\/refs\/heads\/main\/keystore\/java\/android\/security\/keystore2\/AndroidKeyStoreCipherSpiBase.java\" target=\"_blank\" rel=\"noopener\">AOSP Keystore cipher code<\/a>, a failed Keystore tag check becomes a bare <code>AEADBadTagException<\/code>. It has no message. The real error sits in its cause. So a crash report may show only the class name.<\/p>\n\n<h2>Cause one: String(bytes) changes the ciphertext before you store it<\/h2>\n\n<p>GCM output is random-looking binary. It isn&#8217;t text in any encoding. Kotlin&#8217;s <a href=\"https:\/\/kotlinlang.org\/api\/core\/kotlin-stdlib\/kotlin.text\/-string.html\" target=\"_blank\" rel=\"noopener\"><code>String(bytes)<\/code><\/a> decodes it as UTF-8 anyway. The Android reference for <a href=\"https:\/\/developer.android.com\/reference\/java\/lang\/String\" target=\"_blank\" rel=\"noopener\"><code>java.lang.String<\/code><\/a> says this decoding always replaces malformed input with the charset&#8217;s replacement string. Random bytes are full of malformed UTF-8 sequences. Each one becomes <code>U+FFFD<\/code>. That character takes three bytes when encoded again.<\/p>\n\n<p>So <code>toByteArray()<\/code> 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&#8217;t be undone either. The replacement character has thrown away the original bytes.<\/p>\n\n<p>That&#8217;s why the first read fails in the same session. At that moment the shared cipher still holds the right IV.<\/p>\n\n<h2>Cause two: cipher.iv belongs to the last encryption, not the stored value<\/h2>\n\n<p>The obvious next step is Base64. Swap <code>String(encrypted)<\/code> for <code>Base64.encode(encrypted)<\/code> 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.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">one token, same instance -> rt_8f2c1d9e4b7a\nrefresh after saving access -> javax.crypto.AEADBadTagException: Tag mismatch\nafter process restart -> java.lang.IllegalArgumentException: src array is null<\/pre>\n\n\n<p>GCM needs the same IV for decryption that encryption used. The vault never stores it. Instead, <code>load()<\/code> reads <code>cipher.iv<\/code> from the shared instance. Per the <a href=\"https:\/\/developer.android.com\/reference\/javax\/crypto\/Cipher\" target=\"_blank\" rel=\"noopener\"><code>Cipher.getIV()<\/code> reference<\/a>, that returns the IV the cipher holds now. It returns <code>null<\/code> if no IV has been set yet.<\/p>\n\n<p>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&#8217;s IV, so the tag check fails. After a restart, the new <code>Cipher<\/code> has never been initialized. <code>getIV()<\/code> returns <code>null<\/code>. The <a href=\"https:\/\/developer.android.com\/reference\/javax\/crypto\/spec\/GCMParameterSpec\" target=\"_blank\" rel=\"noopener\"><code>GCMParameterSpec<\/code> constructor<\/a> throws <code>IllegalArgumentException<\/code> 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.<\/p>\n\n<p>A hard-coded IV won&#8217;t work with a Keystore key either. <a href=\"https:\/\/developer.android.com\/reference\/android\/security\/keystore\/KeyGenParameterSpec.Builder#setRandomizedEncryptionRequired(boolean)\" target=\"_blank\" rel=\"noopener\"><code>KeyGenParameterSpec.Builder<\/code><\/a> 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 <code>getIV()<\/code>. The Keystore&#8217;s own GCM code also refuses to encrypt twice with one IV. That check is in <a href=\"https:\/\/android.googlesource.com\/platform\/frameworks\/base\/+\/refs\/heads\/main\/keystore\/java\/android\/security\/keystore2\/AndroidKeyStoreAuthenticatedAESCipherSpi.java\" target=\"_blank\" rel=\"noopener\">AndroidKeyStoreAuthenticatedAESCipherSpi<\/a>. The IV is random per value, so it has to travel with the value.<\/p>\n\n<h2>The fix: store the IV with the ciphertext, as Base64<\/h2>\n\n<p>Read the IV after <code>init<\/code>, 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 <code>Cipher<\/code>. Nothing then depends on what the last call left behind.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">class TokenVault(private val key: SecretKey, private val prefs: SharedPreferences) {\n\n    fun save(name: String, token: String) {\n        val cipher = Cipher.getInstance(TRANSFORMATION)\n        cipher.init(Cipher.ENCRYPT_MODE, key)        \/\/ the provider picks a fresh IV\n        val iv = cipher.iv                           \/\/ 12 bytes for GCM\n        val encrypted = cipher.doFinal(token.encodeToByteArray())\n        prefs.edit { putString(name, Base64.encode(iv + encrypted)) }\n    }\n\n    fun load(name: String): String? {\n        val stored = prefs.getString(name, null)?.let { Base64.decode(it) } ?: return null\n        val iv = stored.copyOfRange(0, IV_SIZE)\n        val encrypted = stored.copyOfRange(IV_SIZE, stored.size)\n        val cipher = Cipher.getInstance(TRANSFORMATION)\n        cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, iv))\n        return cipher.doFinal(encrypted).decodeToString()\n    }\n\n    private companion object {\n        const val TRANSFORMATION = \"AES\/GCM\/NoPadding\"\n        const val IV_SIZE = 12\n        const val TAG_BITS = 128\n    }\n}\n\n\/\/ The Keystore key the vault receives.\nfun vaultKey(): SecretKey {\n    val keyStore = KeyStore.getInstance(\"AndroidKeyStore\").apply { load(null) }\n    (keyStore.getKey(\"token_vault\", null) as? SecretKey)?.let { return it }\n    val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, \"AndroidKeyStore\")\n    generator.init(\n        KeyGenParameterSpec.Builder(\n            \"token_vault\",\n            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,\n        )\n            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)\n            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)\n            .setKeySize(256)\n            .build()\n    )\n    return generator.generateKey()\n}<\/pre>\n\n\n<p><code>Base64<\/code> here is <code>kotlin.io.encoding.Base64<\/code>. 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&#8217;s IV was 12 bytes. Then we flipped one bit of a stored value. That read failed with <code>AEADBadTagException<\/code>, as it should.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">refresh after saving access -> rt_8f2c1d9e4b7a\nafter process restart -> at_31c0aa7e\nprovider IV length: 12\ntampered value -> javax.crypto.AEADBadTagException: Tag mismatch<\/pre>\n\n\n<p>The tampered read shows how to handle the exception in production. After the fix, an <code>AEADBadTagException<\/code> 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 <a href=\"https:\/\/grindloop.ai\/blog\/encryptedsharedpreferences-keypermanentlyinvalidatedexception\/\">KeyPermanentlyInvalidatedException<\/a> covers the other way a Keystore key stops decrypting.<\/p>\n\n<h2>How to walk an interviewer from the exception to the fix<\/h2>\n\n<p>This snippet works well in a live debugging round. The interviewer says token reads fail with <code>AEADBadTagException<\/code>. Our post on <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">how the Android debugging round is scored<\/a> explains why the second bug matters. A strong answer goes in this order.<\/p>\n\n<ol>\n<li>Say what the exception proves. GCM verifies a tag over the ciphertext. Failure means the key, IV or bytes differ from encryption time.<\/li>\n<li>Check the bytes first. <code>String(encrypted)<\/code> decodes binary as UTF-8. Malformed sequences become <code>U+FFFD<\/code>, so the bytes change. Use Base64.<\/li>\n<li>Check the IV next. <code>cipher.iv<\/code> is the IV of the last <code>init<\/code>. It&#8217;s wrong after a second save and <code>null<\/code> after a restart.<\/li>\n<li>Give the fix. Store the IV with the ciphertext, split it off on load and use a new <code>Cipher<\/code> per call.<\/li>\n<li>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.<\/li>\n<li>Name the test that would have caught it. Save two values, then read the first from a new vault instance.<\/li>\n<\/ol>\n\n<h2>Wrong answers that hide one bug and keep the other<\/h2>\n\n<ul>\n<li>&#8220;Use Base64 and you&#8217;re done.&#8221; It fixes cause one. Our run still failed on the second token and after a restart.<\/li>\n<li>&#8220;Turn off <code>setRandomizedEncryptionRequired<\/code> and use a constant IV.&#8221; The IV problem goes away because every value shares one IV. The <code>KeyGenParameterSpec.Builder<\/code> reference explains the cost. Equal plaintexts then give equal ciphertexts. That leaks information about the plaintext.<\/li>\n<li>&#8220;Keep the <code>Cipher<\/code> as a field and reuse it.&#8221; Sharing the instance is what made the wrong IV available. A new instance per call costs little and holds no leftover state.<\/li>\n<li>&#8220;Catch <code>AEADBadTagException<\/code> and return <code>null<\/code>.&#8221; Before the fix, that turns a bug in your code into users who are silently signed out. Catch it only once the code can&#8217;t cause it.<\/li>\n<li>&#8220;The Keystore key must be broken.&#8221; The key was fine in our repro. Both failures came from the code around it.<\/li>\n<\/ul>","protected":false},"excerpt":{"rendered":"<p>AEADBadTagException on decrypt? String(bytes) corrupts AES-GCM ciphertext and a shared cipher.iv gives the wrong IV. Repro, Keystore fix and interview answer.<\/p>\n","protected":false},"author":2,"featured_media":912,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"AEADBadTagException When Decrypting a Saved Token With Android Keystore AES-GCM","rank_math_description":"AEADBadTagException on decrypt? String(bytes) corrupts AES-GCM ciphertext and a shared cipher.iv gives the wrong IV. Repro, Keystore fix and interview answer.","rank_math_focus_keyword":"aeadbadtagexception","footnotes":""},"categories":[9,5],"tags":[15,87,16,59,12,58,45],"class_list":["post-911","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-security","tag-android","tag-debugging-interview","tag-interview-prep","tag-keystore","tag-kotlin","tag-security","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/911","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=911"}],"version-history":[{"count":1,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/911\/revisions"}],"predecessor-version":[{"id":913,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/911\/revisions\/913"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/912"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=911"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=911"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=911"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}