Skip to content
Commitwise
Menu
Android Development

Android app security

Keep tokens and keys safe with the Android Keystore, exclude secrets from backups, bind biometrics to keys with a CryptoObject, lock down network traffic with the Network Security Config and certificate pinning, and protect exported components, intents, PendingIntents and WebViews, with Play Integrity for server-side trust.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A penetration test of the banking app lists five findings. The refresh token sits in plain SharedPreferences. Auto Backup copies it to the user’s cloud backup. A debug network_security_config that trusts user-installed certificates shipped in the release. An exported activity loads any URL it receives into a WebView with a JavaScript bridge. And a PendingIntent for a notification is mutable, so another app could change where it leads.

Android gives apps strong tools: the Keystore keeps keys in hardware, the Network Security Config controls trust declaratively, and the manifest decides what other apps can reach. Most real vulnerabilities come from not using them, or from one line that turns them off. This lesson goes through the common ones and their fixes.

New to some of these? Open what you need, or skip ahead.

Basics:What is a token?

After you sign in, the server gives the app a token: a long random string that proves who you are on later requests. An access token lives minutes or hours; a refresh token lasts longer and gets new access tokens. Anyone who steals one can act as the user until it expires. See JWT (JSON Web Token)JWT (JSON Web Token)A signed token that carries claims (who the user is, what they may do, when it expires), so a server can verify a request without a database lookup.Open in glossary →.

Basics:What is an intent?

An intent is a message that starts an activity, a service or a broadcast receiver, inside your app or in another app. A component that other apps may start is exported (android:exported="true" in the manifest). Anything an exported component receives comes from code you don’t control.

Part Not started

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:

  1. Create a key in the Keystore (once).
  2. Encrypt the token with it.
  3. 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.gradle can 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>
  • KeyGenerator with "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.xml keeps the token file out of cloud backups and phone-to-phone transfers.
Spot the bugEasy to write, easy to steal

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")
    }
}

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()?

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.

Exercisemedium

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
  1. Encrypt the token with a Keystore key before storing it (or reuse TokenStore), instead of plain SharedPreferences.
  2. 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.
  3. Add backup rules that exclude the token store from cloud backup and device transfer, and handle decryption failures as “connect again”.
NeedUse
Tokens and small secretsAES-GCM with a Keystore key; ciphertext in DataStore (or Tink with a Keystore master key)
Data released only after biometricsKeystore key with setUserAuthenticationRequired + BiometricPrompt.CryptoObject
Strongest hardwaresetIsStrongBoxBacked(true) where available
BackupsdataExtractionRules (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

  1. Where does the key that encrypts the token live?

  2. Why exclude the encrypted token from backups?

  3. What makes BiometricPrompt protect data rather than just show a dialog?

  4. What’s the status of EncryptedSharedPreferences?

Tokens and keys don't go in plain SharedPreferences or files. Generate a key in the Android Keystore (hardware-backed where available, never exportable), encrypt the token with AES-GCM and store the ciphertext in DataStore. Exclude secrets from Auto Backup and device transfer with dataExtractionRules, since restored ciphertext can't be decrypted on another device. Bind biometrics to a key with BiometricPrompt and a CryptoObject. Secrets compiled into the APK are public.

Part Not started

Network trust and what other apps can reach

Network: since Android 9, apps can’t use plain http:// by default. The Network Security ConfigNetwork Security ConfigAn Android XML file that declares which certificates the app trusts, whether cleartext is allowed, and which keys are pinned.Open in glossary →, an XML file, controls who the app trusts:

  • Release builds trust only the system’s certificate authorities, so a fake certificate installed by malware or a public Wi-Fi portal isn’t accepted.
  • Debug builds may also trust user-installed certificates, so you can inspect traffic with a proxy while developing.
  • Pinning goes further: the app accepts only your server’s keys. Always add a backup pin, or a key change on the server breaks every request until users update.

Other apps: your app’s activities, services and receivers can be started by other apps if they’re exported. Anything they send is untrusted:

Network: cleartextTrafficPermitted is false by default since API 28; release trust anchors should be system only, with user certificates added in a <debug-overrides> block. Pinning via <pin-set> (SPKI SHA-256, at least one backup, an expiration after which pinning stops being enforced rather than bricking old app versions) or OkHttp’s CertificatePinner; pin intermediate CAs if leaf keys rotate often; coordinate a rotation runbook with whoever owns certificates. Components: since API 31, android:exported must be explicit; export only entry points, protect internal IPC with signature-level permissions, validate all extras and URIs (path traversal in ContentProviders and FileProvider paths, intent redirection when forwarding a received Intent), use explicit intents for internal communication, and PendingIntent.FLAG_IMMUTABLE (required for most uses since API 31) so receivers can’t fill in or redirect them. WebViews: keep JavaScript off unless needed, never expose addJavascriptInterface to untrusted origins, restrict navigation to an allowlist, disable file access (allowFileAccess = false), and prefer Custom Tabs for third-party pages. Device trust: root and tamper detection are speed bumps; the Play Integrity API gives your server a signed verdict about the app binary, the device and the Play install, bound to a request nonce, which is what fraud-sensitive endpoints should check.

// A notification that opens an order: explicit intent, immutable PendingIntent
val intent = Intent(context, MainActivity::class.java).apply {
    action = Intent.ACTION_VIEW
    data = "https://shop.example.com/orders/$orderId".toUri()
}
val pending = PendingIntent.getActivity(
    context, orderId.hashCode(), intent,
    PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)

// An exported deep-link activity: only our own pages, only https
private fun safeUrl(intent: Intent): Uri? {
    val uri = intent.data ?: return null
    return uri.takeIf { it.scheme == "https" && it.host == "shop.example.com" }
}
<!-- res/xml/network_security_config.xml (android:networkSecurityConfig in the manifest) -->
<network-security-config>
    <base-config cleartextTrafficPermitted="false">
        <trust-anchors>
            <certificates src="system" />                <!-- release: system CAs only -->
        </trust-anchors>
    </base-config>

    <domain-config>
        <domain includeSubdomains="true">api.example.com</domain>
        <pin-set expiration="2027-06-30">                 <!-- after this date, pins aren't enforced -->
            <pin digest="SHA-256">r/mIkG3eEpVdm+u/ko/cwxzOMo1bk4TyHIlByibiA5E=</pin>
            <pin digest="SHA-256">YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=</pin>   <!-- backup key -->
        </pin-set>
    </domain-config>

    <debug-overrides>
        <trust-anchors>
            <certificates src="user" />                  <!-- proxies, only in debuggable builds -->
        </trust-anchors>
    </debug-overrides>
</network-security-config>
  • base-config blocks http:// and trusts only the system’s certificate authorities.
  • pin-set pins two keys for api.example.com: the current one and a backup. The expiration date is a safety net: if the app is still installed after that date with old pins, it stops enforcing them instead of failing every request.
  • debug-overrides applies only to debug builds, so the release can’t be inspected with a user-installed proxy certificate.
  • FLAG_IMMUTABLE and an explicit intent (MainActivity::class.java) mean the notification always opens your activity with your data.
  • safeUrl accepts only https links to your own domain; anything else is ignored.

Production puzzles

Spot the bugAn exported browser

Tap the line with the bug.

// <activity android:name=".HelpActivity" android:exported="true" />
class HelpActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val webView = WebView(this).apply {
            settings.javaScriptEnabled = true
            addJavascriptInterface(AccountBridge(session), "Account")
        }
        setContentView(webView)
        webView.loadUrl(intent.getStringExtra("url") ?: HELP_URL)
    }
}

Predict the output

The app pins api.example.com with a single pin and no expiration attribute. The backend team rotates to a new key on a Friday. Users on the current app version open it on Saturday. What happens?

Exercisehard

Harden a fintech app

A payments app: login, card details behind biometrics, transfers, push notifications that open transactions, and a help center in a WebView. List the controls you’d put in place, on the device and on the server.

›

Go through storage, network, components, the WebView, the device itself and the API.

SolutionTry it yourself first
  • Storage: refresh token encrypted with a Keystore key in DataStore, excluded from backups; card data decrypted only through a CryptoObject with a strong-biometric key invalidated on enrollment changes.
  • Network: system CAs only in release, pinning with backup pins and an expiration for the payments API, no cleartext.
  • Components: only the launcher and App Links activities exported; every extra and URI validated; immutable explicit PendingIntents for notifications; no intent forwarding.
  • WebView: help center on an allowlist of our own URLs, no JavaScript bridge (or origin-restricted message listeners), file access off; external links in Custom Tabs.
  • Device trust: Play Integrity verdicts with a server nonce on login and transfers; root checks only as a signal.
  • Server: short-lived tokens with revocation, device binding, transfer limits and risk scoring, idempotency keys, a signed challenge from a Keystore key for high-value transfers.
  • Process: no secrets in the APK or logs, dependency scanning, and a release-build security test pass.
Exerciseeasy

Fix the notification

This code builds a notification’s tap action: PendingIntent.getActivity(context, 0, Intent("com.example.OPEN_ORDER").putExtra("id", orderId), PendingIntent.FLAG_MUTABLE). What’s wrong, and how would you write it?

›

Two things: how the target activity is found, and whether the PendingIntent can be changed.

SolutionTry it yourself first
  • The intent is implicit (an action string), so the system resolves it to whatever app handles that action, possibly not yours.
  • FLAG_MUTABLE lets whoever receives the PendingIntent fill in extra details. Notifications don’t need that.
  • The request code is always 0, so notifications for different orders reuse the same PendingIntent.
val intent = Intent(context, OrderActivity::class.java).putExtra("id", orderId)
val pending = PendingIntent.getActivity(
    context, orderId.hashCode(), intent,
    PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
  • Cleartext off (default API 28+); release trusts system CAs only; user CAs in <debug-overrides>.
  • Pins: SPKI SHA-256, a backup, an expiration; or OkHttp CertificatePinner. Rotation runbook.
  • Components: explicit exported (API 31+), export only entry points, signature permissions for internal IPC, validate all extras/URIs, no intent redirection, explicit intents, FLAG_IMMUTABLE PendingIntents.
  • WebView: JS off by default, no bridges for untrusted origins (origin-restricted addWebMessageListener), allowlisted navigation, file access off, Custom Tabs for third parties.
  • Play Integrity verdicts with a server nonce; root detection is only a signal.

Check this part

  1. Why should release builds not trust user-installed certificates?

  2. What does FLAG_IMMUTABLE do for a notification’s PendingIntent?

  3. What does the expiration attribute on a pin-set do after the date passes?

  4. An exported activity loads intent.getStringExtra("url") into a WebView with a JS bridge. Risk?

Since API 28 cleartext HTTP is blocked by default; keep user-installed CAs out of release trust. Pin public keys in the Network Security Config with a backup pin and an expiration, or with OkHttp's CertificatePinner. Export only components that must be exported, validate every incoming intent, use FLAG_IMMUTABLE PendingIntents and explicit intents, and don't load untrusted URLs into WebViews with JavaScript bridges. Play Integrity lets your server check requests come from your genuine app.

Key takeaways

  • Encrypt tokens with a Keystore key and keep them out of backups and logs.
  • Nothing inside the APK is secret.
  • Release builds trust only system certificates; pin important APIs with a backup pin.
  • Export only the components that must be reachable, and check everything they receive.
  • Use immutable, explicit PendingIntents.
  • Bind biometrics to keys with CryptoObject; handle invalidated keys.
  • Plan pin rotation and expirations before you ship pins.
  • Treat every exported component, intent and WebView page as an attack surface.
  • Let the server decide trust with Play Integrity and its own checks.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.