Security cheat sheet
Key ideas
- AndroidKeyStore holds keys per app UID;
load(null)needs no file or password. - AES-GCM with a Keystore-generated IV prevents IV reuse; store the 12-byte IV alongside ciphertext.
security-cryptois deprecated; use Tink'sAndroidKeysetManagerwith DataStore or raw Keystore + AES-GCM.- Ship at least two certificate pins per host (current + backup) in NSC and/or OkHttp
CertificatePinner. - Use AppAuth with Custom Tabs and PKCE for OAuth; never ship a client secret in the APK.
- Biometric-bound keys require
BIOMETRIC_STRONGand aCryptoObject; a new enrollment invalidates them by default. - Set
android:exported="false"on internal components; Android 12+ requires the attribute on every intent-filter component. - A pin is the SHA-256 of the DER-encoded SubjectPublicKeyInfo, not the whole certificate; renewing with the same key keeps it valid.
KeyPermanentlyInvalidatedExceptionmeans the key is unrecoverable; delete the alias and re-authenticate the user.- NSC and OkHttp
CertificatePinnerare independent; if both are configured, both must pass.
APIs at a glance
| API or term | Use it for |
|---|---|
AndroidKeyStore | Open the platform keystore per app UID; no file or password needed. |
KeyGenParameterSpec | Build AES-GCM key specs with purpose, block mode, and auth parameters. |
GCMParameterSpec | Pass the 12-byte IV and 128-bit tag length to Cipher.init for decryption. |
CertificatePinner (OkHttp) | Enforce public-key pins on a host inside a specific OkHttpClient. |
network-security-config (NSC) | Platform-level pinning and cleartext rules covering all connections. |
AppAuth (net.openid:appauth) | Run OAuth PKCE via Custom Tabs without shipping a client secret. |
BiometricPrompt + CryptoObject | Gate a Keystore key behind a Class 3 biometric prompt per operation. |
KeyPermanentlyInvalidatedException | Catch at Cipher.init when an auth-bound key is invalidated; delete and re-create. |
android:exported | Control cross-app reachability; mandatory on Android 12+ for intent-filter components. |
assetlinks.json | Serve over HTTPS to verify App Links; fingerprint must match the Play signing key. |
FLAG_IMMUTABLE | Mark every PendingIntent non-mutable unless the receiver fills in data. |
StrongBoxUnavailableException | Catch when no StrongBox exists; fall back to a TEE-backed key. |
Snippets
Keystore AES-GCM encrypt / decrypt
private const val ALIAS = "notes_key"
fun getOrCreateKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(keyStore.getKey(ALIAS, null) as? SecretKey)?.let { return it }
val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
gen.init(
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build()
)
return gen.generateKey()
}
fun encrypt(plaintext: ByteArray): ByteArray {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())
return cipher.iv + cipher.doFinal(plaintext)
}
fun decrypt(blob: ByteArray): ByteArray {
val iv = blob.copyOfRange(0, 12)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(128, iv))
return cipher.doFinal(blob, 12, blob.size - 12)
}OkHttp CertificatePinner with backup pin
val pinner = CertificatePinner.Builder()
.add(
"api.example.com",
"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=",
)
.build()
val client = OkHttpClient.Builder()
.certificatePinner(pinner)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()Biometric-bound Keystore key
// setUserAuthenticationParameters needs API 30+
fun createBiometricKey(alias: String): SecretKey {
val spec = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setKeySize(256)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setUserAuthenticationRequired(true)
.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
.build()
val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
gen.init(spec)
return gen.generateKey()
}NSC with pin expiry and debug overrides
<network-security-config>
<domain-config>
<domain includeSubdomains="true">api.example.com</domain>
<pin-set expiration="2027-06-30">
<pin digest="SHA-256">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</pin>
<pin digest="SHA-256">BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=</pin>
</pin-set>
</domain-config>
<debug-overrides>
<trust-anchors><certificates src="user" /></trust-anchors>
</debug-overrides>
</network-security-config>Rules of thumb
- Prefer Tink's
AndroidKeysetManageror raw Keystore + AES-GCM over the deprecatedsecurity-cryptolibrary. - Never store a client secret or API key in the APK; keep secrets server-side and issue short-lived tokens.
- Always check
containsAliasbefore generating a Keystore key so you do not overwrite it and lose encrypted data. - Ship at least two pins per host (current + backup) so a planned key rotation does not break installed apps.
- Never launch an
Intenttaken fromgetParcelableExtra; build a new explicitIntentfrom validated values. - Prefer
FLAG_IMMUTABLEon everyPendingIntentunless the receiver must fill in data such as inline reply.
Gotchas
- Reusing a GCM IV with the same key. Two encryptions with the same key and IV leak plaintext information and allow tag forgery; let the Keystore generate a fresh IV each time and store it with the ciphertext.
- Ignoring KeyPermanentlyInvalidatedException. A new biometric enrollment or removed lock screen invalidates the key; catch it at
Cipher.init, delete the alias, and re-authenticate the user because the old ciphertext cannot be recovered. - Pinning only in one OkHttp client. Other
OkHttpClientinstances andHttpsURLConnectionbypass it; add NSC pins to cover every connection that uses the platform TLS stack (native TLS code may ignore NSC too). - Using BIOMETRIC_WEAK for Keystore keys. Class 2 biometrics cannot unlock Keystore keys; use
BIOMETRIC_STRONGwith aCryptoObject, optionally plusDEVICE_CREDENTIAL. - Forgetting android:exported on components with intent filters. Apps targeting Android 12+ fail to install without an explicit declaration; set
falsefor internal screens andtrueonly for required entry points. - Using the upload-key fingerprint in assetlinks.json. With Play App Signing the fingerprint must match the Play app signing key, or verification fails and links open in the browser on Android 12+.
Quick interview answers
Why is security-crypto deprecated and what should I use instead?
EncryptedSharedPreferences and EncryptedFile were deprecated in 2025, so new code should not start on them. Use Tink's AndroidKeysetManager with DataStore, or implement Keystore + AES-GCM directly.
How do I pin a certificate in Android?
A pin is the base64 SHA-256 of the DER-encoded SubjectPublicKeyInfo, not the whole certificate. Ship at least two pins per host in NSC or OkHttp CertificatePinner, and set an expiration date in NSC so old builds stop enforcing stale pins.
What happens when a user enrolls a new biometric and I use a biometric-bound key?
The key is invalidated by default (setInvalidatedByBiometricEnrollment is true), and Cipher.init throws KeyPermanentlyInvalidatedException. Catch it, delete the alias, and send the user through full sign-in because the old ciphertext cannot be recovered.
How should I handle OAuth in an Android app?
Use AppAuth with Custom Tabs and PKCE; never run OAuth in a WebView and never ship a client secret. Register the app as a public client so the code_verifier and S256 code_challenge are generated client-side.
Why must I set android:exported on components with intent filters?
Apps targeting Android 12+ must declare android:exported explicitly on every component with an intent filter, or the app cannot be installed. Set it to false for internal screens and true only for entry points that other apps or the system need.
What is the difference between NSC pinning and OkHttp CertificatePinner?
They are independent mechanisms; if both are configured, both must pass for a connection to succeed. NSC covers every connection that uses the platform TLS stack, including HttpsURLConnection, while CertificatePinner only applies to the specific OkHttpClient it is attached to.