Storing tokens and secrets on device

Security Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

A new app stores a refresh token in SharedPreferences in plain text. What's the best fix for 2026?

Options
Hint 1 of 1

Where should the encryption key live?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Encrypt it with an AES key from Android Keystore, store the ciphertext in DataStore, and exclude it from backup

Correct. The key stays in secure hardware and the token isn't copied to other devices.

Why not the others?
  • B Switch to EncryptedSharedPreferences. That library is deprecated; don't start new code on it.
  • C Base64-encode the token. Encoding isn't encryption.
  • D Move it to external storage. Other apps or users could read it.

30-second answer

Keep secrets in app-private storage (DataStore or a file) encrypted with a key from the Android Keystore, so the key never leaves secure hardware. Jetpack Security's EncryptedSharedPreferences is now deprecated, so new code uses Keystore directly or a library like Tink. Never put secrets in external storage, logs, or plain SharedPreferences, and exclude them from backups.

Practise saying it · 30 s. No recording, just a timer

Explain secure storage on Android.

Say your answer out loud, then check which of these points you covered:

  • Keystore key, private storage
  • EncryptedSharedPreferences deprecated
  • Exclude from backup
  • Short-lived tokens

Deep dive

App-private storage is sandboxed, but rooted devices and backups can still expose plain files.

Encrypt with AES-GCM using a Keystore key; store only the ciphertext and IV.

Use android:dataExtractionRules (Android 12+) or fullBackupContent to exclude token files from cloud backup and device transfer.

Prefer short-lived access tokens plus a refresh token, so a leak expires.

Common mistakes

  • Tokens in plain SharedPreferences or logs.
  • Writing secrets to shared or external storage.
  • Assuming encryption helps if the key is hard-coded in the app.

Senior take & follow-ups

Say Keystore holds the key, encrypted data lives in private storage, and mention the deprecation and backup rules.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does a hard-coded key not help?

    Show hint

    Anyone can decompile the app and read it.

  2. Why exclude tokens from backup?

    Show hint

    A restored backup on another device could carry a live session.

Similar on iOS: Storing secrets in the Keychain iOS stores secrets in the Keychain directly; Android stores encrypted data and keeps only the key in Keystore.

Suggest a fix if something here is wrong or out of date.