Skip to content

Lesson 5 of 13 · 12m

Keystore and Keychain: Doing It Right

Android Keystore and the iOS Keychain keep key bytes in hardware and hand you a handle — accessibility classes, biometric gating, and synchronizable flags decide who can ever read them.

The key never enters your process

The Android Keystore is not a file format. KeyGenParameterSpec.Builder(alias, PURPOSE_ENCRYPT or PURPOSE_SIGN) generates key material inside the KeyMint (formerly Keymaster) service — on a TEE, or on a discrete Secure Element if the hardware has one — and hands you back a handle. Encrypt/decrypt calls go to the hardware-backed daemon; the raw key bytes never exist in your address space. Malware that achieves code execution in your process can ask the daemon to perform operations while the device is unlocked. It cannot extract the key to ship home.

That asymmetry — operations yes, bytes no — is the entire point, and it's the thing file-level encryption can never give you.

Relevant builder calls and what they buy:

KeyGenParameterSpec.Builder("tok_key", PURPOSE_ENCRYPT or PURPOSE_DECRYPT)
    .setBlockModes(BLOCK_MODE_GCM)
    .setEncryptionPaddings(ENCRYPTION_PADDING_NONE)
    .setUserAuthenticationRequired(true)
    .setUserAuthenticationParameters(0, AUTH_BIOMETRIC_STRONG)
    .setInvalidatedByBiometricEnrollment(true)
    .setIsStrongBoxBacked(true)   // Pixel 3+, Android 9+, separate SE
    .build()

setUserAuthenticationRequired gates every use behind a fresh auth event — validity 0 means "authenticate per op" via a BiometricPrompt + CryptoObject (the duration-based shortcut only works for AUTH_DEVICE_CREDENTIAL). setInvalidatedByBiometricEnrollment kills the key if a new fingerprint enrolls — that's the check against "attacker adds their finger." setIsStrongBoxBacked requests the SE; on devices without one the call throws StrongBoxUnavailableException, so catch and degrade to TEE deliberately, not silently.

EncryptedSharedPreferences wrapped this pattern for you, but androidx.security:security-crypto was deprecated by Google in 2024 — write the Keystore + AES-GCM shim yourself (it's ~40 lines), or use Tink.

The iOS shape

The Keychain is an encrypted SQLite store whose keys derive from the Secure Enclave. What controls exposure is the accessibility class on the item:

  • kSecAttrAccessibleWhenUnlockedThisDeviceOnly — item readable only while the device is unlocked, never migrates to backups or restores. The correct default for session tokens.
  • kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly — readable in background after first unlock post-boot; needed for background fetch, weaker.
  • kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly — readable only while a passcode is set; removing the passcode deletes the item.
  • The non-ThisDeviceOnly variants migrate via encrypted backups — which is either the point or the bug, depending on what you stored.

kSecAttrAccessControl with .biometryCurrentSet binds an item to the enrolled biometric set — new fingerprint, item invalidated. .userPresence accepts biometrics or device passcode; pick deliberately. kSecAttrSynchronizable ships the item through iCloud Keychain to every device the account touches — the flag to audit when a secret shows up on a laptop.

Two platform quirks worth knowing cold: keychain items survived app uninstall before iOS 10.3 (they're cleared now), and apps sharing a Team ID share keychain-access-groups — your sibling apps can read each other's items if you add them to a shared group. Convenience and attack surface are the same checkbox.

The wrong model

"Encrypt the database" is the sentence that gets teams in trouble. Encryption-at-rest with the key stored next to the ciphertext — or derivable inside the same process — buys you nothing against an attacker running code in your app. Keychain/Keystore move the trust boundary: the adversary needs to use the device while unlocked and biometric-authenticated, not merely read its flash. Forensic tooling bears this out — Cellebrite and friends image files and plists easily; ThisDeviceOnly keychain items are the part of the dump that stays empty.

Practice

Session tokens and user secrets: WhenUnlockedThisDeviceOnly, plus AccessControl when the threat model justifies the prompt. Android: Keystore AES-GCM with AUTH_BIOMETRIC_STRONG for high-value keys, TEE otherwise, EncryptedSharedPreferences gone. Audit synchronizable and access groups. And remember what this doesn't do — it protects key material. An attacker on an unlocked device can still ride authenticated operations; that's why the server still verifies everything the client sends.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.