Storing secrets and the Keystore

Learn how to store secrets on Android: Keystore keys with KeyGenParameterSpec, AES-GCM, Tink with DataStore, and why API keys in an APK are never secret. About 25 minutes.

Why it matters

  • Anything compiled into an APK can be read back. Tools such as apktool and jadx recover strings from BuildConfig, strings.xml and native libraries. Interviewers ask how you protect an API key, and the honest answer is: keep it on your server.
  • EncryptedSharedPreferences and EncryptedFile from androidx.security:security-crypto were deprecated in 2025. New code should use Android Keystore keys directly, or Tink with a Keystore-backed master key and DataStore.
  • The Android Keystore keeps key material out of your app's process, often inside secure hardware (TEE or StrongBox). Knowing what it does and does not protect is a common senior interview topic.
  • Keystore keys can become unusable (KeyPermanentlyInvalidatedException) when the lock screen is removed or a new biometric is enrolled. Apps that do not handle it get stuck or crash.

The simple explanation

  • A hotel safe: the safe keeps the key, and you only get to ask it to lock or unlock things. You never carry the key around.
  • On many phones the safe is built into a vault (TEE or StrongBox) that even the hotel's own staff (the Android OS and your app) cannot open.
  • A note taped to the safe door (a string in the APK) is readable by anyone who walks past.
  • If you remove the lock on your room (disable the lock screen), the hotel voids safes that required it, and you must set up a new one.

How do you store secrets securely on Android? Generate an encryption key inside the Android Keystore, use it to encrypt the data with AES-GCM, and store only the ciphertext (in DataStore, a file or a database). The key is created with KeyGenParameterSpec, lives in the Keystore system service, and your app only holds a Key handle. On devices with secure hardware the raw key bytes never leave the TEE or StrongBox, so they cannot be copied out of the device even if app storage is read.

KeyGenParameterSpec.Builder sets the alias, purposes, key size, block mode, padding and access rules. Useful access rules:

  • setUserAuthenticationRequired(true) with setUserAuthenticationParameters(timeout, types) (API 30+) makes the key usable only after the user authenticates. A timeout of 0 means every use needs a BiometricPrompt with a CryptoObject (see the authentication lesson).
  • setIsStrongBoxBacked(true) (API 28+) asks for a key in a StrongBox secure element. If the device has none, generateKey() throws StrongBoxUnavailableException, so retry without it.
  • setUnlockedDeviceRequired(true) (API 28+) blocks key use while the device is locked.

For symmetric encryption use AES/GCM/NoPadding. GCM gives confidentiality and integrity. Let the Keystore pick a random 12-byte IV (by default it refuses a caller-supplied IV for encryption), and store the IV next to the ciphertext.

Instead of EncryptedSharedPreferences: Tink (com.google.crypto.tink:tink-android) wraps its keyset with a Keystore master key through AndroidKeysetManager, gives you an Aead that handles IVs and key rotation, and you store the ciphertext in DataStore.

Secrets shipped inside an APK are not secret. R8 renames classes and members but leaves string constants readable. API keys for paid services, OAuth client secrets and signing keys belong on your server; the app holds a short-lived token issued after the user signs in.

ToolProtects againstDoes not protect against
Keystore key (TEE or StrongBox)Copying the key off the deviceYour own code decrypting and leaking plaintext
setUserAuthenticationRequiredUse of the key without a recent user authenticationMalware running after the user unlocks the key
R8 / ProGuardReadable class and method namesReading string constants from the APK
Keeping the secret on a serverExtraction from the APKA compromised server or a stolen user token

Notes

  • KeyStore.getInstance("AndroidKeyStore").apply { load(null) } opens the Keystore. There is no file or password; the system service holds the keys for your app's UID.
  • Create an AES key with KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"), PURPOSE_ENCRYPT or PURPOSE_DECRYPT, BLOCK_MODE_GCM and ENCRYPTION_PADDING_NONE.
  • Check containsAlias before generating, or you replace the key and lose access to everything encrypted with the old one.
  • GCM must never reuse an IV with the same key. Let the Keystore generate it, read it from cipher.iv, and store it with the ciphertext.
  • Decrypt with GCMParameterSpec(128, iv). A modified ciphertext fails with AEADBadTagException instead of returning garbage.
  • setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG) means a Class 3 biometric on every use. Add or KeyProperties.AUTH_DEVICE_CREDENTIAL to also accept the PIN, pattern or password.
  • KeyPermanentlyInvalidatedException is thrown by Cipher.init when an auth-bound key was invalidated: the secure lock screen was removed, or (for biometric keys) a new biometric was enrolled. Delete the alias, create a new key and ask the user to sign in again, because the old ciphertext cannot be recovered.
  • security-crypto (EncryptedSharedPreferences, EncryptedFile) is deprecated. Use Tink's AndroidKeysetManager plus DataStore, or your own Keystore + AES-GCM code.
  • A secret in BuildConfig, strings.xml, local.properties injected at build time, or a native .so is still in the APK. Restrict the key in the provider's console (package name and signing certificate) if it must ship, or proxy calls through your backend.
  • Hardware backing is not guaranteed. On API 31+ check KeyInfo.securityLevel (SECURITY_LEVEL_TRUSTED_ENVIRONMENT or SECURITY_LEVEL_STRONGBOX) if your threat model needs it.

Code example

This object creates an AES-256-GCM key in the Android Keystore (StrongBox if available, TEE otherwise) and encrypts and decrypts a value with the IV stored in front of the ciphertext. It is the kind of key you use to encrypt a token at rest in DataStore.

import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.security.keystore.StrongBoxUnavailableException
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
 
object TokenCipher {
    private const val ALIAS = "token_key"
    private const val TRANSFORMATION = "AES/GCM/NoPadding"
    private const val IV_SIZE = 12
    private const val TAG_BITS = 128
 
    private val keyStore: KeyStore =
        KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
 
    private fun getOrCreateKey(): SecretKey {
        (keyStore.getKey(ALIAS, null) as? SecretKey)?.let { return it }
        return try {
            generateKey(strongBox = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
        } catch (e: StrongBoxUnavailableException) {
            generateKey(strongBox = false) // no StrongBox on this device: use the TEE
        }
    }
 
    private fun generateKey(strongBox: Boolean): SecretKey {
        val builder = KeyGenParameterSpec.Builder(
            ALIAS,
            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
        )
            .setKeySize(256)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
        if (strongBox) builder.setIsStrongBoxBacked(true)
        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
        generator.init(builder.build())
        return generator.generateKey()
    }
 
    fun encrypt(plaintext: ByteArray): ByteArray {
        val cipher = Cipher.getInstance(TRANSFORMATION)
        cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey()) // Keystore picks a random IV
        return cipher.iv + cipher.doFinal(plaintext)       // [12-byte IV][ciphertext + tag]
    }
 
    fun decrypt(blob: ByteArray): ByteArray {
        val iv = blob.copyOfRange(0, IV_SIZE)
        val cipher = Cipher.getInstance(TRANSFORMATION)
        cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(TAG_BITS, iv))
        return cipher.doFinal(blob, IV_SIZE, blob.size - IV_SIZE)
    }
}
  • The key is created once and looked up by alias afterwards; the app never sees its bytes.
  • StrongBoxUnavailableException is thrown by generateKey(), not by the builder, so the fallback wraps the generation call.
  • The IV comes from the Keystore and is stored in the first 12 bytes of the blob, so each encryption uses a fresh one.
  • This key has no user-authentication requirement, so it can decrypt in the background. For a key gated by a fingerprint, add setUserAuthenticationRequired(true) and pass the Cipher through BiometricPrompt with a CryptoObject; calling doFinal without that throws.
  • Store the returned bytes (for example Base64-encoded) in DataStore, not the plaintext token.

Run the idea in plain Kotlin

The JVM has no Android Keystore, so an in-memory AES key stands in for it. The flow is the same: a fresh IV per encryption, the IV stored with the ciphertext, and tampering detected by GCM.

import javax.crypto.AEADBadTagException
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec

const val IV_SIZE = 12

// Stands in for a key that would live in the Android Keystore
val key: SecretKey = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey()

fun encrypt(plaintext: ByteArray): ByteArray {
  val cipher = Cipher.getInstance("AES/GCM/NoPadding")
  cipher.init(Cipher.ENCRYPT_MODE, key) // provider generates a random IV
  return cipher.iv + cipher.doFinal(plaintext)
}

fun decrypt(blob: ByteArray): ByteArray {
  val cipher = Cipher.getInstance("AES/GCM/NoPadding")
  cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, blob.copyOfRange(0, IV_SIZE)))
  return cipher.doFinal(blob, IV_SIZE, blob.size - IV_SIZE)
}

fun main() {
  val token = "refresh-token-123".toByteArray()
  val first = encrypt(token)
  val second = encrypt(token)

  println("Blob size = 12 (IV) + " + token.size + " (data) + 16 (tag) = " + first.size)
  println("Same plaintext, same blob twice? " + first.contentEquals(second))
  println("Decrypted: " + String(decrypt(first)))

  val tampered = first.copyOf()
  tampered[IV_SIZE] = (tampered[IV_SIZE].toInt() xor 1).toByte()
  try {
      decrypt(tampered)
      println("Tampered blob accepted")
  } catch (e: AEADBadTagException) {
      println("Tampered blob rejected: AEADBadTagException")
  }
}

Expected output:

Blob size = 12 (IV) + 17 (data) + 16 (tag) = 45
Same plaintext, same blob twice? false
Decrypted: refresh-token-123
Tampered blob rejected: AEADBadTagException

In production

Paid API key extracted from the release APK
  • A third-party API key was injected into BuildConfig from a Gradle property and shipped in the release build.
  • The team assumed R8 made the string unreadable. Decompiling the APK with jadx showed the key as a plain string constant.
  • Someone reused the key from their own scripts, and the usage bill climbed until the provider's quota alerts fired.
The fix
  • Revoked the leaked key and issued a new one that only the backend knows.
  • Moved the third-party call behind a backend endpoint; the app now calls it with the user's short-lived access token, and the backend applies rate limits per user.
  • Added a release CI step that decompiles the APK and fails the build if a known key prefix appears.
Biometric-bound key invalidated after a new fingerprint
  • A banking app encrypted its refresh token with a key created with setUserAuthenticationRequired(true) and AUTH_BIOMETRIC_STRONG.
  • Users who enrolled a new fingerprint found the app stuck on a spinner: Cipher.init threw KeyPermanentlyInvalidatedException, and the code only caught UserNotAuthenticatedException.
  • The exception is by design: by default, enrolling a new biometric invalidates biometric-bound keys, so a person who knows the PIN cannot add their own fingerprint and unlock the token.
The fix
  • Caught KeyPermanentlyInvalidatedException around Cipher.init, deleted the alias with keyStore.deleteEntry, and cleared the stored ciphertext.
  • Sent the user through a full sign-in, then created a new key and encrypted the new refresh token with it.
  • Added an instrumented test that deletes and recreates the key between encrypt and decrypt to exercise the recovery path.

Common mistakes

  • Storing an API key in BuildConfig or strings.xml. It is readable in the APK. R8 renames code but leaves string constants intact. Keep the key server-side and give the client a short-lived token.
  • Starting new code on EncryptedSharedPreferences. The library is deprecated. Use Tink with a Keystore master key and DataStore, or Keystore + AES-GCM directly.
  • Ignoring KeyPermanentlyInvalidatedException. Auth-bound keys are invalidated when the lock screen is removed or a new biometric is enrolled. Catch it at Cipher.init, delete the key, and re-authenticate the user.
  • Reusing a GCM IV. Two encryptions with the same key and IV leak information about both plaintexts and allow tag forgery. Let the Keystore generate the IV and store it with the ciphertext.
  • Generating the key on every launch. Without a containsAlias or getKey check, you overwrite the key and can no longer decrypt saved data.
  • Assuming StrongBox exists. Many devices have no StrongBox. Catch StrongBoxUnavailableException from generateKey() and fall back to a TEE-backed key.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How does the Android Keystore protect a key from the application?”

“When does a Keystore key throw KeyPermanentlyInvalidatedException?”

“A codebase stores a JWT in EncryptedSharedPreferences. What do you change?”

“How do you keep a third-party API key out of attackers' hands?”

Quiz

What does setUserAuthenticationRequired(true) do on a Keystore key?

Which cipher configuration fits a Keystore AES key for encrypting a token?

A team puts a paid third-party API key in BuildConfig. What is true?

Cipher.init throws KeyPermanentlyInvalidatedException for a biometric-bound key. What should the app do?

0 of 4 answered

Mini task

Encrypt a token with a Keystore key (20 min)

  1. In an Android app (min SDK 28 or higher, so the StrongBox calls need no version check), add the TokenCipher object from the example.
  2. Add a Preferences DataStore with one key, encrypted_token. Write a TokenStore class with suspend fun save(token: String) that stores Base64.encodeToString(TokenCipher.encrypt(...), Base64.NO_WRAP) and suspend fun read(): String? that decodes and decrypts it.
  3. Save a fake token, restart the app, and read it back. Log only whether it matched, never the token itself.
  4. Corrupt the stored value by changing one character, then read again. Catch AEADBadTagException and treat it as "no token".
  5. Add a clear() function that deletes the DataStore entry and calls keyStore.deleteEntry("token_key"), and call it on sign-out.

Done condition: the token survives an app restart, a corrupted value is rejected without a crash, and sign-out removes both the ciphertext and the key.

Next: Network security and pinning