Skip to content

Lesson 2 of 6 · 9 min read

Protecting Data on Mobile Devices

Free lessonReviewed By the AISecurityInterviews editorial team
Reading position
In this lesson

TL;DR: Store less: short-lived tokens in memory, one refresh token or device key on disk. Keep keys in hardware: Android Keystore (TEE or StrongBox) and the iOS Keychain or Secure Enclave, non-exportable, optionally requiring user authentication. Encrypt what persists with those keys and exclude secrets from backups. Hardware backing stops a key being copied; it does not stop a compromised app using it. Then close the side doors, where most leaks happen: logs, crash reports, SDKs, backups, screenshots, clipboard, keyboard caches, URLs and notifications.

Before you read

Pick an answer before you read further. The lesson below explains it, and guessing first, right or wrong, helps the explanation stay with you.

  1. 1An app stores its refresh token, base64-encoded, in SharedPreferences. What protects it?

Decide what must exist on the device

Most apps need a way to stay signed in and nothing else. Access tokens live minutes and stay in memory; a refresh token or a device-bound key persists. Never ship long-lived server secrets in the app; no storage mechanism protects a value every user already has.

Platform storage

Android.

  • Generate keys inside the Keystore (KeyGenParameterSpec); request StrongBox for a separate secure chip where available. Keys are non-exportable; key attestation proves to a server that a key lives in hardware.
  • Encrypt the refresh token with an AES-GCM Keystore key before writing it to app-private storage.
  • setUserAuthenticationRequired makes a key usable only after biometric or device credential, for high-value operations.
  • Exclude sensitive files from backup and device transfer with backup rules.

iOS.

  • Keychain items with deliberate accessibility classes: WhenUnlockedThisDeviceOnly for most secrets (unavailable while locked, never migrates through backups); AfterFirstUnlock only if background refresh needs it.
  • Secure Enclave keys (P-256) for signing and key agreement; the private key never leaves the coprocessor; access control can require biometry or passcode.
  • File protection classes for files that hold sensitive data.

iOS Data Protection classes: when is a file readable?

iOS encrypts every file with its own key, and wraps that key with a class key. The class decides when the class key is available, which decides when the file can be read. The four classes, from Apple's Platform Security guide:

ClassConstantClass key availableTypical use
A: Complete ProtectionNSFileProtectionCompleteOnly while unlocked; discarded 10 seconds after lock (with "Require Password: Immediately")Secrets the app only needs in the foreground
B: Protected Unless OpenNSFileProtectionCompleteUnlessOpenNew files can be written while locked; a file already open stays readable until closedDownloading an attachment in the background
C: Until First User AuthenticationNSFileProtectionCompleteUntilFirstUserAuthenticationFrom the first unlock after boot until the next rebootThe default for app data not assigned another class
D: No ProtectionNSFileProtectionNoneAlways; protected only by the device's hardware UID keyMainly enables fast remote wipe

The practical consequence is the one interviewers want: Class C protects against an attacker who has to reboot the phone, and nothing else. A phone that was unlocked once this morning and then locked has its Class C keys in memory. If your refresh token sits in a default-class file, "the phone is locked" does not protect it.

LESSON · PROTECTING DATA ON MOBILE DEVICES
What a locked iPhone can still read
  1. 1

    1 · Powered on, never unlocked

    before first unlock

    • Class A, B, C files: unreadable
    • Class D files: readable

    Strongest state for a seized or stolen phone

  2. 2

    2 · Unlocked and in use

    user is holding it

    • Every class readable
    • Device security is the user's session

    Malware or a coerced user sees everything

  3. 3

    3 · Locked after first unlock

    the usual state in a pocket

    • Class A: unreadable 10 s after lock
    • Class C: still readable
    • Class B: open files only

    Default-class data is exposed here

  4. 4

    4 · Rebooted

    keys dropped from memory

    • Back to the first state
    • Class C keys gone until the next unlock

    Why forensic tools prefer a phone that was never switched off

1/4

Before first unlock

Only Class D is readable. The passcode, entangled with the hardware UID key, has not been entered.

Keychain items follow the same pattern with different names. kSecAttrAccessibleWhenUnlocked corresponds to Class A, AfterFirstUnlock to Class C. The ThisDeviceOnly variants are wrapped with the device's hardware UID key in backups, so they restore unusable on another phone. WhenPasscodeSetThisDeviceOnly items are never synced to iCloud Keychain or backed up, and are deleted if the user removes the passcode, which makes them the right home for a device-binding secret. Keychain sharing between apps is possible only for apps from the same developer, enforced through access-group entitlements.

Android: file-based encryption and the Keystore

File-based encryption (FBE) arrived in Android 7.0 and is mandatory for devices launching with Android 10 or later. It gives each app two storage areas:

  • Credential Encrypted (CE) storage, the default, is available only after the user unlocks the device once since boot (the Android analogue of Class C).
  • Device Encrypted (DE) storage is available during Direct Boot, before the first unlock, for things like alarms and accessibility settings. Do not put secrets there.

The Android Keystore keeps key material out of the app process entirely: the app holds a handle and sends data to be signed, encrypted or decrypted. With a Trusted Execution Environment (TEE) or StrongBox backing it, the key never leaves secure hardware, so even a compromised OS can use the key but not extract it. Details worth knowing:

  • StrongBox (Android 9 and later) is a separate secure chip with its own CPU, storage, true random number generator, tamper resistance and secure timer. It supports fewer algorithms (RSA 2048, AES 128 and 256, ECDSA and ECDH on P-256, HMAC-SHA256, 3DES) and is slower; Google advises using it only when the threat model needs it.
  • Biometric-bound keys are invalidated by default when a new fingerprint or face is enrolled, so someone who adds their own biometric to an unlocked phone cannot use the key.
  • Version binding ties keys to the OS version and patch level; rolling the device back to an older, vulnerable OS makes them unusable.
  • Key attestation (since Keymaster 2 in Android 7.0) produces a certificate chain, rooted in a Google key, that lets your server verify a key really lives in hardware and with which properties. The client trust and attestation lesson covers what that proves.

What hardware backing guarantees

LESSON · PROTECTING DATA ON MOBILE DEVICES
A device-bound key in use

What an attacker gets

Token copied from storage or logs

  • No private key to sign with
  • Requests from another device fail

Malware inside the app process

  • Can ask the hardware to sign
  • Cannot copy the key out
1/4

The app asks the hardware to sign

The private key never leaves the secure hardware; the app only gets a signature back.

Hardware backing means the key cannot be exported, even by root, so a stolen token without the key is useless when the server requires device signatures. It does not mean the key cannot be used: malware or an attacker controlling the app process on an unlocked device can ask the hardware to sign or decrypt. Requiring user authentication per use narrows that window.

Backups: the copy you forgot about

Backups are a second storage location with different protection, and they are easy to overlook.

  • Android Auto Backup is on by default for apps targeting Android 6.0 and later (android:allowBackup defaults to true) and copies up to 25 MB per app to the user's cloud account, end-to-end encrypted with the screen-lock credential from Android 9 on devices that support it. Cache directories and the no_backup directory are always excluded.
  • From Android 12, on some devices allowBackup="false" disables cloud backup but not device-to-device transfer. Use dataExtractionRules with separate <cloud-backup> and <device-transfer> sections to exclude secrets from both.
  • Google recommends its Block Store API, rather than files or shared preferences, for credentials that should survive a phone migration.
  • On iOS, ThisDeviceOnly Keychain items and Secure Enclave keys never usefully leave the device, so a restore onto a new phone forces re-enrolment. Design for that: it is the security property, not a bug.

The side doors

ChannelControl
Logs and crash reportsStrip debug logging from release builds, redact, configure crash SDK scrubbing
Analytics and ad SDKsInventory, minimise, review what they send; they run with the app's access
BackupsBackup rules (Android), this-device-only classes and file protection (iOS)
App-switcher screenshotsFLAG_SECURE on Android; cover the view on iOS when backgrounding
ClipboardAvoid copying secrets; clear; mark as sensitive
Keyboard caches and autofillSecure text entry, no suggestions on sensitive fields
URLsTokens in headers or bodies, never query strings
WebView storageClear cookies and caches on logout
NotificationsGeneric text on the lock screen

Worked example: auditing a fintech app

Exercise login, view a statement and log out on a test device with a test account, then search everything for the test refresh token's value: the app's files (encrypted, good), logcat (found in a debug-level network log that ships in release: finding), the cloud backup (excluded, good), crash reporter payloads (found in a breadcrumb: finding), and analytics events (account number in a screen-view event: finding). Storage was fine; three side doors were open.

Worked example: the lost-phone matrix

A banking app persists one refresh token. Compare three ways of storing it across five situations.

SituationToken in a default-class (C) fileToken in a Class A file, encrypted with a hardware keyDevice-bound P-256 key with per-use user authentication
Phone found powered offProtectedProtectedProtected
Phone found locked, unlocked earlier todayExposed to anyone who can read storageProtected (Class A key discarded 10 s after lock)Protected
Unlocked; malware in a different appProtected by the sandboxProtected by the sandboxProtected by the sandbox
Malicious SDK inside the banking appExposedExposed (the app can decrypt)Key usable only with the user's biometric, never copyable
Owner roots the phoneExposedUsable on this device, not copyableUsable on this device with authentication, not copyable

The table shows what each layer buys. Class A narrows the time window. The sandbox handles other apps. Nothing on the device stops code inside the app from using what the app can use, but hardware keys stop it being copied, so the server sees every request come from one enrolled device and can revoke that device alone. Add a sixth row for backups: Auto Backup would copy the default-class file unless excluded, while the hardware key restores unusable elsewhere.

Misconceptions interviewers listen for

  • "Data Protection is on, so files are safe on a stolen phone." Default-class data is readable after the first unlock until reboot.
  • "Hardware-backed means the key can't be misused." It means it can't be exported. Code in the app, or a compromised OS, can still ask for operations.
  • "allowBackup=false stops data leaving the device." Not for device-to-device transfer on some Android 12+ devices; use data extraction rules.
  • "Encrypted storage means we're done." Storage is one channel; logs, SDKs, screenshots and URLs are the usual leaks.
  • "StrongBox is always better than the TEE." It resists physical attack better and is slower with fewer algorithms. Choose per threat model.

What if · interview follow-ups

Hold your answer as the constraints change

You are reviewing how a banking app stores its refresh token and device credentials on Android and iOS. The interviewer changes one condition at a time.

  1. Start here

    What if the token is in an ordinary app file with the default protection and the phone is stolen while locked?

Primary references

References for the mechanisms discussed above, accessed 6 November 2026:

How this shows up in interviews

"How do you store tokens on mobile?" and "where does data leak from a mobile app?" are common. Interviewers check deliberate storage choices, an exact statement of what hardware backing protects, and whether you look past storage to logs, SDKs and backups.

Say it in 30 seconds: "Store as little as possible: short-lived tokens in memory and one refresh token or device key on disk. Keys go in the Keystore or Keychain and Secure Enclave, non-exportable and, for high-value use, behind user authentication; secrets are encrypted with them and excluded from backups. Hardware means the key can't be copied, not that it can't be used. Then I check the side doors, because that's where leaks actually happen: logs, crash reports, SDKs, backups, screenshots, clipboard and URLs."

Check yourself

Say or write your answer first, then reveal. Explaining it from memory, in your own words, is the skill an interviewer is checking.

  1. 1Why prefer WhenUnlockedThisDeviceOnly over AfterFirstUnlock for a Keychain item holding a session secret?

  2. 2A pentester finds the session token in an analytics event payload. Which control failed, and how do you fix it?

  3. 3What does iOS Data Protection Class C protect against, exactly?

  4. 4Why are Android Keystore keys bound to the OS version and patch level?

  5. 5What is the difference between credential-encrypted and device-encrypted storage on Android?

Practise it as an interviewer asks it

Related lessons