Storing secrets
SharedPreferences is a plain XML file in the app’s folder. Normal apps can’t read it, but backups, rooted phones and forensic tools can. A token there is like a house key under the doormat.
The Android KeystoreAndroid KeystoreThe Android system that creates and keeps cryptographic keys, often in secure hardware, without ever exposing them to the app.Open in glossary → is a safe built into the phone. You ask it to create a key, and the key never leaves it: on most devices it lives in secure hardware, and even your own app can’t read the key’s bytes. It can only ask the Keystore to encrypt or decrypt with it.
So the pattern is:
- Create a key in the Keystore (once).
- Encrypt the token with it.
- Store the encrypted token in DataStore or SharedPreferences.
Two more things:
- Backups: Android backs up app data to the user’s Google account. Exclude your secrets, because the key isn’t backed up, so the restored data can’t be decrypted anyway.
- Keys in the app: an API key written in your code or
build.gradlecan be pulled out of the APK in minutes. Real secrets belong on your server.
The Android Keystore generates non-exportable keys, hardware-backed (TEE, or StrongBox with setIsStrongBoxBacked(true) where present), with use constraints in KeyGenParameterSpec: purposes, block modes, setUserAuthenticationRequired with a timeout or per-use authentication, setInvalidatedByBiometricEnrollment, setUnlockedDeviceRequired. Encrypt secrets with AES-256-GCM using a Keystore key and store the ciphertext (with its IV) in DataStore. Jetpack Security’s EncryptedSharedPreferences is deprecated; use the Keystore directly or Tink (whose Android integration wraps a keyset with a Keystore master key). Backups: Auto Backup and device-to-device transfer copy app data but never Keystore keys, so restored ciphertext fails with AEADBadTagException or KeyPermanentlyInvalidatedException-style errors; exclude secret stores in dataExtractionRules (API 31+) and fullBackupContent (older), and treat decryption failure as “signed out”, never a crash. For biometrics to protect data rather than show a dialog, create the key with setUserAuthenticationRequired(true) and pass a Cipher in BiometricPrompt.CryptoObject; only an authenticated cipher can decrypt. Anything in the APK (API keys, “obfuscated” secrets, R8 or not) is extractable.
class TokenStore(private val dataStore: DataStore<Preferences>) {
private val tokenKey = stringPreferencesKey("refresh_token")
private val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
private fun secretKey(): SecretKey =
(keyStore.getEntry(ALIAS, null) as? KeyStore.SecretKeyEntry)?.secretKey
?: KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build()
)
}.generateKey()
suspend fun save(token: String) {
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, secretKey()) }
val bytes = cipher.iv + cipher.doFinal(token.toByteArray()) // 12-byte IV, then ciphertext
dataStore.edit { it[tokenKey] = Base64.encodeToString(bytes, Base64.NO_WRAP) }
}
suspend fun load(): String? {
val stored = dataStore.data.first()[tokenKey] ?: return null
return try {
val bytes = Base64.decode(stored, Base64.NO_WRAP)
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, bytes, 0, 12))
}
String(cipher.doFinal(bytes, 12, bytes.size - 12))
} catch (e: GeneralSecurityException) {
dataStore.edit { it.remove(tokenKey) } // restored from another device, or key invalidated
null // treat as signed out, never crash
}
}
private companion object { const val ALIAS = "refresh_token_key" }
}<!-- res/xml/data_extraction_rules.xml (android:dataExtractionRules in the manifest) -->
<data-extraction-rules>
<cloud-backup>
<exclude domain="file" path="datastore/auth.preferences_pb" />
</cloud-backup>
<device-transfer>
<exclude domain="file" path="datastore/auth.preferences_pb" />
</device-transfer>
</data-extraction-rules>KeyGeneratorwith"AndroidKeyStore"creates the key inside the Keystore. The app only ever holds a reference to it.- AES-GCM encrypts the token and also detects tampering. The random IV (12 bytes) is stored in front of the ciphertext, because decryption needs it.
catch (GeneralSecurityException): if decryption fails, for example after restoring a backup on a new phone where the key doesn’t exist, the app forgets the token and asks the user to sign in, instead of crashing.data_extraction_rules.xmlkeeps the token file out of cloud backups and phone-to-phone transfers.
Tap the line with the bug.
class AuthRepository(context: Context) {
private val prefs = context.getSharedPreferences("auth", Context.MODE_PRIVATE)
fun onLoggedIn(accessToken: String, refreshToken: String) {
prefs.edit { putString("refresh_token", refreshToken) }
Log.d("Auth", "Logged in, token=$accessToken")
}
}Hint: Who can read SharedPreferences files and logcat?
- Line 5: the refresh token is stored in plain text.
MODE_PRIVATEstops other normal apps, but not backups (Auto Backup includes it by default), rooted devices or forensic extraction. - Line 6: the access token goes to logcat, which ends up in bug reports, on test devices shared between people, and in crash tools that collect logs.
Encrypt with a Keystore key (as in TokenStore above), exclude the file from backups, and never log secrets. Log that a user signed in, not with what.
Predict the output
A user gets a new phone and restores everything from a Google backup, including the app's DataStore with the encrypted token. The Keystore key was created on the old phone. What happens when the app calls load()?
Keystore keys never leave the device: they aren't backed up or transferred. secretKey() creates a new key, and decrypting the old ciphertext with it fails (GCM detects the wrong key). That's why secret stores are excluded from backups, and why decryption failures must mean 'sign in again', not a crash. Without the catch, every restored user would crash on launch.
Biometrics that protect data
BiometricPrompt alone returns a callback in your process, which a hooked app on a rooted device can fake. Binding it to a key makes the hardware enforce it:
val spec = KeyGenParameterSpec.Builder("card_key", KeyProperties.PURPOSE_DECRYPT or KeyProperties.PURPOSE_ENCRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setUserAuthenticationRequired(true) // every use needs authentication
.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
.setInvalidatedByBiometricEnrollment(true) // new fingerprint → key invalid
.build()
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.DECRYPT_MODE, cardKey(), GCMParameterSpec(128, iv))
}
BiometricPrompt(activity, executor, object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
val authenticated = result.cryptoObject?.cipher ?: return
showCard(String(authenticated.doFinal(ciphertext))) // only works after a real match
}
}).authenticate(
BiometricPrompt.PromptInfo.Builder()
.setTitle("Show card details")
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
.setNegativeButtonText("Cancel")
.build(),
BiometricPrompt.CryptoObject(cipher),
)Handle KeyPermanentlyInvalidatedException when initializing the cipher: a new fingerprint or a removed screen lock invalidates the key, and the data must be re-fetched or re-enrolled.
Review the settings code
A pull request adds a “Connected accounts” feature: it stores a partner API’s OAuth token in SharedPreferences, puts the partner’s client secret in BuildConfig from build.gradle.kts, and leaves android:allowBackup="true" with no backup rules. Write three review comments.
›
Think about what’s readable from the APK, what’s readable from the device, and what’s copied to backups.
SolutionTry it yourself first
- Encrypt the token with a Keystore key before storing it (or reuse
TokenStore), instead of plainSharedPreferences. - The client secret isn’t secret in the APK. Anyone can decompile it. The token exchange that needs the client secret should happen on our server, which then gives the app only what it needs.
- Add backup rules that exclude the token store from cloud backup and device transfer, and handle decryption failures as “connect again”.
| Need | Use |
|---|---|
| Tokens and small secrets | AES-GCM with a Keystore key; ciphertext in DataStore (or Tink with a Keystore master key) |
| Data released only after biometrics | Keystore key with setUserAuthenticationRequired + BiometricPrompt.CryptoObject |
| Strongest hardware | setIsStrongBoxBacked(true) where available |
| Backups | dataExtractionRules (API 31+) and fullBackupContent excluding secret stores |
EncryptedSharedPreferences(Jetpack Security) is deprecated.- Keystore keys never back up or transfer: decryption failure after restore = signed out, not a crash. Handle
KeyPermanentlyInvalidatedException. - Nothing in the APK is secret; no secrets in logcat.
Check this part
Where does the key that encrypts the token live?
Why exclude the encrypted token from backups?
What makes BiometricPrompt protect data rather than just show a dialog?
What’s the status of EncryptedSharedPreferences?