Skip to content
Commitwise
Menu

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:

  1. Generate an AES-256 key in the Android Keystore (KeyGenParameterSpec with GCM, no padding). The key is non-exportable and usually hardware-backed; the app only holds a reference.
  2. Encrypt the token with AES/GCM/NoPadding; store the IV together with the ciphertext, Base64-encoded, in DataStore.
  3. 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

Esc

Type to search the whole site.