← The playbook

Security

Hardening an Android app: Keystore and beyond

Most Android security guides are a list of APIs in no particular order. A list can't tell you which of them actually protects your users. I've built secure storage for production apps held to strict compliance standards, and what worked every time was starting from the threat and working back to the control.

Start with the threat model

Threat scenarioAttacker capabilityPrimary controls
Lost or stolen devicePhysical possession, possibly device passcodeKeystore keys bound to device unlock and biometric authentication
Malicious app on same deviceSending Intents, reading shared storage, drawing overlaysUnexported components, strict Intent validation, internal storage
Untrusted networkRogue Wi-Fi access point or TLS proxyCleartext disabled, restricted trust anchors, managed pinning
Rooted device or repackaged APKFull runtime instrumentation and memory inspectionServer-side Play Integrity & key attestation, minimal local secrets
Cloud backups & device transferExtracting app files off the physical deviceExplicit data-extraction-rules exclusions

Everything below answers one of those rows. If a control doesn't answer any of them for your app, leave it out.

What the Keystore protects

The Android Keystore creates and holds keys inside secure hardware, either a Trusted Execution Environment or a dedicated StrongBox chip. The raw key never enters your app's memory. You hand the Keystore some bytes, it encrypts or signs them, and you get the result back.

KVaultKey.ktKotlin
val spec = KeyGenParameterSpec.Builder(    "vault_master_key",    KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,)    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)    .setKeySize(256)    .setUnlockedDeviceRequired(true)    .build()val key = KeyGenerator    .getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")    .apply { init(spec) }    .generateKey()

The builder is where your policy lives. These are the options I think about for every key:

  • setUnlockedDeviceRequired(true) makes the key useless while the screen is locked.
  • setUserAuthenticationRequired(true) demands a biometric or device credential before the key will work.
  • setInvalidatedByBiometricEnrollment(true) destroys the key when a new fingerprint or face is enrolled.
  • setIsStrongBoxBacked(true) asks for the dedicated chip. Not every device has one, so catch StrongBoxUnavailableException and fall back to the default hardware backing.

What it doesn't protect

This is the part people miss. The Keystore stops someone extracting the key. It doesn't stop someone using it. Malware running as your app on a compromised device can still ask the Keystore to decrypt, because as far as the Keystore can tell, it is your app. The only defense is the usage conditions above, and for the data that matters most, a fresh user authentication.

Envelope encryption for real data

Calling into secure hardware for every database read is slow. So production storage uses two keys.

Where each key livesand what reaches the disk
Secure hardware
Master keyCreated in the Keystore. Never leaves.
App memory
Data keyRandom AES-256. Unwrapped for the session, then dropped.
Disk
Wrapped data key + IVs
CiphertextSQLCipher database, files, DataStore
master key wraps the data key → data key encrypts your data → only wrapped and encrypted bytes are stored
Someone who copies the disk gets nothing they can open without the hardware key.
KVaultCipher.ktKotlin
fun encrypt(plaintext: ByteArray, key: SecretKey): Pair<ByteArray, ByteArray> {    val cipher = Cipher.getInstance("AES/GCM/NoPadding")    cipher.init(Cipher.ENCRYPT_MODE, key) // Keystore generates a fresh random IV    return cipher.iv to cipher.doFinal(plaintext)}fun decrypt(iv: ByteArray, ciphertext: ByteArray, key: SecretKey): ByteArray {    val cipher = Cipher.getInstance("AES/GCM/NoPadding")    cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, iv))    return cipher.doFinal(ciphertext)}

That is what happens underneath. Three rules keep it honest:

  • Never reuse an IV with the same key. In AES-GCM, one repeat breaks both secrecy and integrity. Let the provider generate it and store it next to the ciphertext.
  • Bind each record to its context. Pass associated data such as a table name or record ID, so ciphertext can't be copied from one record into another.
  • Use Google Tink for the data-key layer instead of wiring up low-level ciphers by hand. And note that Jetpack's EncryptedSharedPreferences is deprecated.

In practice I let Tink do the envelope work. The Keystore holds the master key, Tink keeps the wrapped data key and generates every IV, and the call site stays small:

KVaultAead.ktcore/security · tink-android
AeadConfig.register()// Tink keeps the data key wrapped by a Keystore master key and handles IVs for youval aead = AndroidKeysetManager.Builder()    .withSharedPref(context, "vault_keyset", "vault_keyset_prefs")    .withKeyTemplate(KeyTemplates.get("AES256_GCM"))    .withMasterKeyUri("android-keystore://vault_master_key")    .build()    .keysetHandle    .getPrimitive(RegistryConfiguration.get(), Aead::class.java)// Associated data binds the ciphertext to its record, so it can't be swapped into another oneval ciphertext = aead.encrypt(plaintext, "profile:$userId".encodeToByteArray())val restored = aead.decrypt(ciphertext, "profile:$userId".encodeToByteArray())

Treat a lost key as a normal day

Keystore keys stop working. A user changes their lock screen and you get KeyPermanentlyInvalidatedException. Someone restores their files onto a new phone and the hardware key isn't there. Neither is a bug. Your storage layer should catch it, wipe the cache it can no longer read, make a new key, and ask the user to sign in again.

KVaultKeys.ktcore/security
sealed interface CipherResult {    data class Ready(val cipher: Cipher) : CipherResult    data object ReauthRequired : CipherResult}fun openCipher(mode: Int, iv: ByteArray? = null): CipherResult {    val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }    val key = keyStore.getKey(ALIAS, null) as? SecretKey ?: return CipherResult.ReauthRequired    val cipher = Cipher.getInstance("AES/GCM/NoPadding")    return try {        if (iv == null) cipher.init(mode, key) else cipher.init(mode, key, GCMParameterSpec(128, iv))        CipherResult.Ready(cipher)    } catch (e: KeyPermanentlyInvalidatedException) {        keyStore.deleteEntry(ALIAS)   // this key can never work again        encryptedCache.clear()        // and nothing it protected can be read        CipherResult.ReauthRequired   // make a new key after the user signs in    }}

The important part is the return type. Callers can't forget the re-authentication path, because the compiler makes them handle it, and a lost key becomes a sign-in screen instead of a crash loop.

Bind the biometric prompt to a key

A biometric prompt that only flips a boolean on success can be bypassed with runtime hooking. Tie it to a key instead. Initialize a Cipher with a Keystore key that requires authentication, and pass it in a CryptoObject:

KBiometricUnlock.ktKotlin
// The key must be created with user authentication required, for example://   .setUserAuthenticationRequired(true)//   .setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {    init(Cipher.ENCRYPT_MODE, key)}prompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))// In onAuthenticationSucceeded, use result.cryptoObject?.cipher.// The key can only be used after the biometric sensor verifies the user.

Backups, network and other apps

<>data_extraction_rules.xmlres/xml
<data-extraction-rules>    <cloud-backup>        <exclude domain="sharedpref" path="session.xml" />        <exclude domain="database" path="vault.db" />    </cloud-backup>    <device-transfer>        <exclude domain="sharedpref" path="session.xml" />        <exclude domain="database" path="vault.db" />    </device-transfer></data-extraction-rules>
  • For the network, set cleartextTrafficPermitted="false" explicitly and trust only system certificates in release builds. Any proxy certificate you need for debugging goes inside <debug-overrides>, as in the config below.
  • For other apps, set android:exported="false" on anything internal, create PendingIntents with FLAG_IMMUTABLE, share files only through FileProvider, and set filterTouchesWhenObscured on sensitive confirm buttons so an overlay can't trick a tap.
  • For integrity, verify Play Integrity tokens and key attestation chains on your server. A root check that lives only in the app can be patched out of a modified APK.
<>network_security_config.xmlres/xml
<network-security-config>    <base-config cleartextTrafficPermitted="false">        <trust-anchors>            <certificates src="system" />        </trust-anchors>    </base-config>    <!-- Only debuggable builds trust user-installed certificates, for a local proxy -->    <debug-overrides>        <trust-anchors>            <certificates src="user" />        </trust-anchors>    </debug-overrides></network-security-config>

Prove it before release

A control you haven't tried to break is a control you're assuming. Before a release that touches storage or networking, I run through the same short list:

Release checkseach one tries to break a row of the threat model
security pass · release candidate
✓ Restore a backup onto a second phoneexpect: sign-in screen, no crash
✓ Change the lock screen, reopen the appexpect: key rebuilt after sign-in
✓ Route the release build through a proxyexpect: every request fails
✓ Read the merged manifestexpect: nothing exported by accident
✓ Pull the app's files off a test deviceexpect: only ciphertext and wrapped keys
most of these take minutes, and together they cover every row of the threat model
The merged manifest is in the build output, under the manifest merger report, and it is the only manifest that ships.

Design for the audit

Compliance standards for cryptography validate the cryptographic module. They don't validate your UI. So I route every encrypt, hash and sign call through one internal CryptoProvider interface in one module. When an auditor asks which validated module and which algorithms the app uses, the answer is one package they can read in an afternoon.