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-
ThisDeviceOnlyvariants 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?
Keep reading
Related articles from the SudoSecurity blog.
They Got Root on a Fully Patched Ivanti VPN and the Integrity Checker Said Everything Was Fine
Volexity caught an attacker chaining zero-days into unauthenticated root on an Ivanti Connect Secure appliance running the latest build. The payload never touched disk, commands rode in over the same HTTPS requests as the exploit, and Ivanti's Integrity Checker reported no modifications.
Gitea Shipped 21 CVEs in One Release and Eleven of Them Are the Same Bug
Gitea 28.3.0 landed November 1 with twenty-one CVE fixes. Read the list and a pattern jumps out: more than half are the same failure repeated across different route handlers, where a token scoped to public data gets handed private data anyway. That's not twenty-one mistakes.
php2shell: The PHP Bug That Fires Before Your Code Runs
Two critical PHP flaws landed October 21 and were in CISA's exploited-vulnerabilities catalog five days later. The 9.2 score isn't the part that should bother you. It's where the bug lives — it goes off while PHP is still assembling $_POST, before a single line of your application has run.
A Certificate Authority's Private Keys Were the Numbers 4, 56 and 66
Eight eMudhra intermediate CA keys turned out to be recoverable from their own public certificates. Not stolen — computable, because the key generation produced almost no entropy. A researcher pulled all eight in under a second and signed a message with each one to prove it.