Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 104 ยท Quality, Performance and Security

Securing Your App

Secure an Android app: the app sandbox, exported components, network security config, Keystore, secrets in builds, WebView risks and Play Integrity, with runnable stand-ins.

An Android app runs on a device you do not control. The user may have rooted it, installed a malicious app next to yours, connected it to a hostile Wi-Fi network, or handed it to a friend. Your job is not to make your app unbreakable, because nothing is, but to make the cheap attacks fail and to keep the damage small when something goes wrong. Security is mostly a set of good defaults plus a few places where one mistake is expensive.

This lesson walks through the platform's protections and the mistakes developers make on top of them: the app sandbox, exported components, network security configuration, the Keystore, secrets in the build, WebView risks and Play Integrity. General secure-coding habits such as input validation and safe handling of untrusted data are covered in Secure Kotlin Code; here we focus on what is specific to Android. The platform APIs need a device, so the Android code and configuration are read-only. The TryIt blocks are plain-Kotlin stand-ins: a model of a key vault and encrypted token storage, a signature check, and an audit of exported components. Each says what is real (the cryptography, for example) and what is imitation (the Android Keystore itself).

The sandbox: your first line of defense

Every app gets its own Linux user id and, on modern versions, its own SELinux domain. Files in your private directory (/data/data/<package> or the app-specific storage you get from filesDir) belong to your uid, so another app cannot read them. That is why you can keep a database or preferences there without extra encryption for most data.

The sandbox is broken by things you choose to share:

  • Exported components: activities, services, receivers and providers that other apps can start.
  • External storage and shared media, which other apps can read with the right permission.
  • Intents you send to other apps and extras you receive from them.
  • Permissions you request (see Runtime Permissions).

On a rooted device the sandbox no longer protects you. Do not store high-value secrets in plain files and assume the sandbox is enough; use the Keystore (below) and keep valuable decisions on your server.

Exported components

A component is exported when apps other than yours can launch or bind to it. Since Android 12 you must say so explicitly for every component that has an intent filter: android:exported is required, and the build fails without it. Components without an intent filter default to not exported.

XML
<!-- read-only example: AndroidManifest.xml -->
<activity android:name=".MainActivity" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name=".PaymentActivity" android:exported="false" />

<service
    android:name=".SyncService"
    android:exported="false" />

The rule is simple: export only what must be reachable from outside, usually the launcher activity and deep link targets. Everything else is exported="false". An exported component must treat its incoming intent as untrusted input: validate extras, never use a received URI or file path without checking it, and never perform sensitive actions just because an intent asks. A common serious bug is an exported activity that accepts an Intent extra and then launches another intent built from it (an intent redirection), which lets an attacker reach your private components.

Other related protections:

  • Use PendingIntent.FLAG_IMMUTABLE unless you really need other apps to fill in fields.
  • Protect exported receivers and providers with a android:permission of your own, ideally with protectionLevel="signature" so only apps signed with your key can use them.
  • For a ContentProvider that serves files, use FileProvider with a narrow path configuration instead of exposing raw file:// paths.

An exported-component audit, as a model

Studio's lint checks catch many manifest mistakes. The stand-in below models the logic behind a manifest audit: a list of components with their flags, and a function that reports the risky ones. Nothing here reads a real manifest.

Kotlin Auditing exported components (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

MainActivity is exported without a permission on purpose: the launcher must be reachable. DebugToolsActivity shows how a forgotten debug screen becomes an entry point for any app on the phone.

Network security

By default, apps targeting recent Android versions block cleartext HTTP, which is the right default. Use HTTPS everywhere, and keep it that way: never add android:usesCleartextTraffic="true" to production. The network security configuration is an XML file that fine-tunes the rules per domain:

XML
<!-- read-only example: res/xml/network_security_config.xml -->
<network-security-config>
    <base-config cleartextTrafficPermitted="false" />

    <!-- Debug builds may talk to a local server -->
    <debug-overrides>
        <trust-anchors>
            <certificates src="user" />
        </trust-anchors>
    </debug-overrides>

    <domain-config>
        <domain includeSubdomains="true">api.example.com</domain>
        <pin-set expiration="2027-06-30">
            <pin digest="SHA-256">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</pin>
            <pin digest="SHA-256">BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=</pin>
        </pin-set>
    </domain-config>
</network-security-config>

You enable it in the manifest with android:networkSecurityConfig="@xml/network_security_config" on <application>. Two ideas deserve care:

  • debug-overrides applies only to debuggable builds. That lets you trust a proxy certificate while testing without weakening production.
  • Certificate pinning (pin-set) makes the app accept only certificates that match known public key hashes, even if a device trusts a rogue certificate authority. It protects against some attacks but is risky: if your server changes keys and you pinned only one, every installed app breaks until it updates. Always include a backup pin and an expiration date, and pin only when your threat model needs it.

Storing sensitive data: the Keystore

Never keep a password or long-lived token in plain SharedPreferences, a text file or a Room column. If the data must be stored on the device, encrypt it with a key that cannot be read out of the device. The Android Keystore system does that: you ask it to generate a key, and the key material stays inside secure hardware (the trusted execution environment or a dedicated chip such as StrongBox) or a protected system service. Your app can use the key to encrypt and decrypt, but it can never read the key bytes, so copying your app's data to another device yields only unreadable ciphertext.

Kotlin
// read-only example: a Keystore-backed AES key (Android only)
private const val ALIAS = "token_key"

fun getOrCreateKey(): SecretKey {
    val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
    (store.getKey(ALIAS, null) as? SecretKey)?.let { return it }

    val spec = KeyGenParameterSpec.Builder(
        ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
    )
        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
        .setKeySize(256)
        .setUserAuthenticationRequired(false)   // true to demand the screen lock or biometrics
        .build()

    return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
        .apply { init(spec) }
        .generateKey()
}

fun encrypt(plain: ByteArray): Pair<ByteArray, ByteArray> {
    val cipher = Cipher.getInstance("AES/GCM/NoPadding")
    cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())
    return cipher.iv to cipher.doFinal(plain)
}

AES-GCM gives you both secrecy and tamper detection, and each encryption gets a fresh random IV that you store next to the ciphertext. You can ask the Keystore to require user authentication (screen lock or biometrics) before each use of a key, which protects the data when the phone is stolen and unlocked later. The Jetpack Security and Tink libraries wrap this plumbing; prefer a maintained library over hand-written crypto whenever you can, and never invent your own algorithm.

A token vault, modeled in plain Kotlin

The Keystore cannot run here, so this stand-in separates the two roles it plays. A FakeKeystore keeps keys inside and exposes only encrypt and decrypt operations, never the key bytes, and a TokenStore saves only ciphertext. The AES-GCM encryption itself is the real JVM implementation; the hardware protection of the key is what is imitated. To keep the output stable, the code prints facts about the ciphertext, not the random bytes.

Kotlin Token storage with a key that never leaves the vault (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The ciphertext does not contain the token text, a round trip returns the original, and flipping one bit makes GCM refuse to decrypt. On a phone the same pattern holds, with one more guarantee: the key itself sits in protected hardware, which this stand-in cannot provide.

Secrets in the build

Anything you put in your APK can be read. Decompilers, strings and a network proxy do not care that you obfuscated the code. That means:

  • API keys that grant real power must not ship in the app. A key in BuildConfig, strings.xml or a Kotlin constant is public. Keep powerful secrets (payment keys, admin tokens, signing keys) on your own server and let the app call your server, which then calls the third-party service.
  • Keys that are designed to be public (a maps key restricted to your package name and signing certificate) are fine, as long as you restrict them in the provider's console.
  • Keep secrets out of version control. Local values live in local.properties or environment variables and are injected at build time (the Secrets Gradle Plugin, or buildConfigField). That keeps them out of git, though it does not hide them inside the shipped app.
  • Never commit a keystore or its passwords. See Signing and Release Builds.
  • Do not log tokens, passwords or personal data. Logcat can be read through adb and, on old versions, by other apps.

WebView risks

A WebView embeds a browser engine in your app, and every page it loads is a potential attacker if you configure it loosely.

  • Enable JavaScript only for content you control (settings.javaScriptEnabled = true is off by default for a reason).
  • Avoid addJavascriptInterface. It exposes Kotlin objects to JavaScript in the page; if the page can be influenced by an attacker, so can your app. If you must use it, annotate methods with @JavascriptInterface, expose the minimum, and load only pages from your own HTTPS origin.
  • Turn off file and content access you do not need: allowFileAccess = false, allowContentAccess = false.
  • Validate every URL before loadUrl, particularly URLs that arrive in an intent or deep link; check scheme and host against an allowlist.
  • Keep the WebView updated through the system (it updates with Play services and Chrome), and consider Custom Tabs instead of a WebView when you only want to show a web page, since they run in the browser's own process and cookies.
Kotlin
// read-only example: a restrained WebView
webView.settings.apply {
    javaScriptEnabled = true       // only because we control this page
    allowFileAccess = false
    allowContentAccess = false
    domStorageEnabled = true
}
webView.webViewClient = object : WebViewClient() {
    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
        val uri = request.url
        val allowed = uri.scheme == "https" && uri.host == "help.example.com"
        return !allowed   // true cancels the navigation
    }
}

Play Integrity and server-side trust

Your server must never trust the client. Anyone can write a script that calls your API, or run a modified copy of your app. The Play Integrity API gives your server evidence about the request: whether the app binary is the one Google Play distributes (app integrity), whether the device is a genuine Android device (device integrity), and whether the app was installed from Play (account details). The flow is:

sequenceDiagram
    participant App
    participant Play as Play Integrity
    participant Server
    App->>Server: Request a nonce
    Server-->>App: nonce (random, one use)
    App->>Play: Request token with the nonce
    Play-->>App: Signed integrity token
    App->>Server: Action plus token
    Server->>Play: Decode and verify the token
    Server-->>App: Allow or refuse

The server issues a nonce, Play signs a verdict that includes it, and only the server decodes and judges it.

Two details matter. The nonce ties a token to one request so it cannot be replayed, and the token must be decoded on your server, never in the app, where an attacker could fake the answer. Use the verdict as one signal in a risk decision, for example to limit a sensitive action, not as an absolute gate: legitimate users on unusual devices exist.

The principle behind it is general: authorization decisions belong on the server. If your app hides a button but the API behind it has no check, the button is decoration.

A signature check, as a model

Verifying "this message came from someone who holds the key" is the basis of many Android checks, from App Links to signed integrity tokens. This stand-in uses real HMAC-SHA-256 to model a server verifying a signed request with a nonce that may be used only once. The real Play Integrity token is signed with Google's keys, not an HMAC; this shows the verification logic.

Kotlin Signed requests, replay and tampering (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first request succeeds. Sending exactly the same bytes again fails because the nonce was consumed. Changing the action invalidates the signature. A new request with a new nonce and a valid signature works again.

A security checklist

  • Export nothing you do not need, and validate every incoming intent.
  • HTTPS only; pin certificates only with a backup pin and an expiry.
  • Encrypt sensitive local data with a Keystore key; do not store passwords at all if a token will do.
  • Treat everything in the APK as public; keep real secrets on the server.
  • Restrict WebView: no unneeded JavaScript, no file access, allowlisted URLs.
  • Decide authorization on the server, and use Play Integrity as one signal.
  • Do not log secrets; ship release builds with R8 and without debuggable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which components should have android:exported="true"?

    Exporting widens your attack surface, so export only what must be reachable from outside and treat incoming intents as untrusted input.
  2. 2. What is the main security benefit of the Android Keystore?

    Keys live in protected hardware or a protected service; the app can ask to use them but cannot extract them, so copied data cannot be decrypted elsewhere.
  3. 3. Where should you keep a payment-provider secret key that can charge cards?

    Everything shipped in the APK can be extracted. Powerful secrets belong on a server you control, and the app talks to that server.
  4. 4. Why does a Play Integrity flow start with a server-issued nonce, and why is the token decoded on the server?

    A single-use nonce stops an attacker from reusing an old valid token, and only a server-side verification is out of the attacker's reach.
  5. 5. Which WebView setting is safest for a page that only shows static help content from your own site?

    Every enabled feature widens what an attacker-controlled page can do. Allowlisting the origin and turning off access you do not need keeps the risk low.

Summary

  • The app sandbox protects private files by uid, but you weaken it with exported components, shared storage and trusting incoming intents.
  • Export only what must be reachable, protect exported pieces with permissions, use immutable pending intents, and validate every intent extra.
  • Use HTTPS only; configure network_security_config.xml, restrict debug overrides to debug builds and pin certificates only with backup pins and an expiry.
  • Encrypt sensitive local data with a Keystore key (AES-GCM, fresh IV per encryption); the app uses the key but cannot read it.
  • Anything in the APK is public: keep powerful secrets on a server, restrict public keys, and never commit keystores or secrets.
  • Lock down WebView: minimal JavaScript, no file access, allowlisted HTTPS URLs, no addJavascriptInterface where avoidable.
  • Authorization lives on the server; Play Integrity (nonce, server-side decode) is one signal for it.
  • The Android APIs are read-only here; the TryIts model component auditing, token storage and signed requests in plain Kotlin.

Next: Accessibility and Localization