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 scenario | Attacker capability | Primary controls |
|---|---|---|
| Lost or stolen device | Physical possession, possibly device passcode | Keystore keys bound to device unlock and biometric authentication |
| Malicious app on same device | Sending Intents, reading shared storage, drawing overlays | Unexported components, strict Intent validation, internal storage |
| Untrusted network | Rogue Wi-Fi access point or TLS proxy | Cleartext disabled, restricted trust anchors, managed pinning |
| Rooted device or repackaged APK | Full runtime instrumentation and memory inspection | Server-side Play Integrity & key attestation, minimal local secrets |
| Cloud backups & device transfer | Extracting app files off the physical device | Explicit 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.
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 catchStrongBoxUnavailableExceptionand 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.
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
EncryptedSharedPreferencesis 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:
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.
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:
// 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> <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 onlysystemcertificates 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, createPendingIntents withFLAG_IMMUTABLE, share files only throughFileProvider, and setfilterTouchesWhenObscuredon 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> <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:
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.