How do you store an auth token securely on Android?
AndroidMid-level
In shortEncrypt it with an AES-GCM key generated in the Android Keystore, store only the ciphertext (for example in DataStore), exclude it from backups, treat decryption failures as signed out, and never log it. EncryptedSharedPreferences is deprecated.
Model answer
The pattern:
- Generate an AES-256 key in the Android Keystore (
KeyGenParameterSpecwith GCM, no padding). The key is non-exportable and usually hardware-backed; the app only holds a reference. - Encrypt the token with
AES/GCM/NoPadding; store the IV together with the ciphertext, Base64-encoded, in DataStore. - Decrypt on read; if it fails, remove the stored value and treat the user as signed out.
Backups: Auto Backup and device transfer copy app files but never Keystore keys, so a restored token can’t be decrypted. Exclude the token store with dataExtractionRules (API 31+) and fullBackupContent, and handle the failure case anyway.
Why not alternatives: plain SharedPreferences ends up in backups and is readable on rooted devices; a key hardcoded in the app can be extracted from the APK; Jetpack Security’s EncryptedSharedPreferences is deprecated (Tink with a Keystore master key is the maintained option).
For high-value data: create the key with setUserAuthenticationRequired(true) and decrypt through BiometricPrompt with a CryptoObject, so only a real biometric match unlocks it. And never write tokens to logcat.
What they're looking for
Keystore-generated non-exportable keys, AES-GCM with the IV, where the ciphertext lives, backup exclusion and its reason, failure handling, and biometrics via CryptoObject for high-value data.
Common mistakes
- Plain SharedPreferences because "it's private to the app".
- Hardcoding a key in the app to encrypt the token.
- Crashing when a restored backup can't be decrypted.
More android questions
- How do you make sure background work in a mobile app stops when the user leaves the screen?Mid-level
- What's the difference between a configuration change and process death on Android, and what survives each?Mid-level
- How would you modularize a large Android app, and how do you keep builds fast?Senior
- What are the main security risks of exported components, intents and WebViews on Android?Senior