Join our Newsletter — 33% off our NHI Course
Home› Guides› Kotlin and Android Secure Coding Guide: Storage, IPC…
Guide Application Security

Kotlin and Android Secure Coding Guide: Storage, IPC and Network Security

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 26 October 2026 17 min read
On this page

Most exploitable Android flaws are written in a few lines of Kotlin: a forwarded Intent, a concatenated SQL string, a zip entry name trusted as a path, or a secret typed into a constant. Platform defaults have improved with every API level, but they cannot fix code that hands attacker-controlled data to a privileged API. This guide is the code-level companion to the Android App Security Guide: where that page covers platform configuration (Keystore security levels, Network Security Configuration, Play Integrity and backups), this one covers the coding patterns that reviewers, linters and tests should catch in Kotlin source. It maps each pattern to the OWASP Mobile Top 10 2024 and MASVS, gives safe and unsafe API choices side by side, and ends with a rollout plan, metrics and a checklist. It is written for Android developers, mobile code reviewers and application security engineers who own secure coding standards. See the Android App Security Guide.

Key takeaways

  • Every entry point is an untrusted input. Intents, deep links, ContentProvider queries, WebView messages, files and archives all carry data another app or website controls. Validate type, shape and authorisation before acting.
  • Never forward an Intent you did not build. Intent redirection lets another app reach your unexported components. Use IntentSanitizer or a PendingIntent, and know that Android 16 (API 36) adds default hardening you should not opt out of.
  • Bind data, never concatenate it. Use selectionArgs, Room @Query parameters and a strict SQLiteQueryBuilder; resolve canonical paths before writing any extracted file.
  • Secrets in code are public. Keys in constants, BuildConfig fields or strings.xml are extracted from the APK. Generate keys in Android Keystore, fetch short-lived tokens from a backend, and keep tokens out of logs and data class toString().
  • The build is part of the code. Gradle dependency verification, R8 with log stripping, release-only lint gates and SDK review stop compromised or leaky components reaching production.

Mapping the OWASP Mobile Top 10 to Kotlin code

The OWASP Mobile Top 10 2024 names the risk categories; the table shows where each one usually lives in an Android codebase and which coding control addresses it. MASVS categories are given so findings can be tracked against the verification standard. See the OWASP Mobile Top 10 Guide.

OWASP Mobile 2024Where it appears in Kotlin and Android codePrimary coding controlMASVS
M1 Improper Credential UsageAPI keys in const val, BuildConfig or resources; tokens in SharedPreferencesKeystore-held keys, backend token exchange, no embedded cloud credentialsMASVS-STORAGE, MASVS-AUTH
M2 Inadequate Supply Chain SecurityUnverified Gradle dependencies, SDKs with embedded keysverification-metadata.xml in strict mode, SDK reviewMASVS-CODE
M3 Insecure Authentication/AuthorizationClient-side role checks, biometric callback treated as proofCredential Manager passkeys, CryptoObject-bound biometrics, server-side authorisationMASVS-AUTH
M4 Insufficient Input/Output ValidationrawQuery string building, zip extraction, deep link parameters, WebView bridgesParameter binding, canonical path checks, allowlist validationMASVS-CODE, MASVS-PLATFORM
M5 Insecure CommunicationCustom TrustManager or HostnameVerifier that accepts everythingPlatform TLS validation plus Network Security ConfigurationMASVS-NETWORK
M6 Inadequate Privacy ControlsPII in logcat, analytics events and crash reportsLog stripping, redacted types, data minimisationMASVS-PRIVACY, MASVS-STORAGE
M7 Insufficient Binary ProtectionsRelease builds without R8, debuggable flags, secrets relying on obfuscationR8 shrinking and obfuscation, no secrets in the binaryMASVS-RESILIENCE
M8 Security MisconfigurationExported components, broad FileProvider paths, permissive WebSettingsandroid:exported="false", narrow paths, explicit WebSettingsMASVS-PLATFORM
M9 Insecure Data StoragePlain files, external storage, persisted Parcels, unencrypted databasesInternal storage plus Keystore AES-GCM for sensitive fieldsMASVS-STORAGE
M10 Insufficient CryptographyHard-coded keys (CWE-321), ECB mode, reused IVsAES/GCM/NoPadding with Keystore-generated IVsMASVS-CRYPTO

Storage, keys and secrets in Kotlin code

Android's guidance on hard-coded cryptographic secrets (CWE-321, MASVS-CRYPTO) is blunt: keys stored as strings or byte arrays in source or in resource files such as strings.xml are extracted by anyone who reverse engineers the APK. Obfuscation slows this down; it does not change the outcome.

  • Generate keys where they live: create keys with KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") and a KeyGenParameterSpec that fixes PURPOSE_ENCRYPT or PURPOSE_DECRYPT, BLOCK_MODE_GCM, ENCRYPTION_PADDING_NONE and setRandomizedEncryptionRequired(true). The code refers to the key only by alias.
  • Store the IV with the ciphertext: with GCM the Keystore generates the IV, so persist cipher.iv next to the ciphertext and pass it back through GCMParameterSpec on decryption. Never supply a fixed IV to work around this.
  • Use KeyChain only for shared credentials: android.security.KeyChain is for system-wide credentials shared across apps (for example enterprise client certificates); app-private keys belong in Android Keystore.
  • Treat BuildConfig as public: buildConfigField and manifestPlaceholders values are compiled into the APK. Use them for environment names and public identifiers, never for API secrets or signing keys. See the Secrets Management Guide.
  • Do not persist Parcels: Parcel is an IPC transport, not a storage format; storing one on disk causes compatibility failures and data loss. Serialise to a defined schema instead.
  • Mind Kotlin data classes: the compiler-generated toString() prints every property, so a data class holding a token, password or card number leaks it the first time it is logged or sent to a crash reporter. Override toString() on sensitive types, or wrap the value in a masking type whose toString() returns a placeholder, as Android's logging guidance recommends.

Logging without leaking

Logs are readable by preloaded apps that hold READ_LOGS and end up in bug reports. Android recommends avoiding android.util.Log in production, logging compile-time constants where possible (ErrorProne's @CompileTimeConstant can enforce this), and routing output through a single sanitiser. Enable R8 for release builds and add an -assumenosideeffects rule for android.util.Log covering isLoggable, v, d and i (and w and e if you remove all logging) in proguard-rules.pro. Gating on BuildConfig.DEBUG is a useful extra, not a replacement for stripping.

Inter-process communication is Android's largest code-level attack surface, because any installed app can send an Intent to an exported component and any web page can trigger a deep link.

PatternUnsafe codeSafe code
Forwarding a nested IntentstartActivity(intent.getParcelableExtra("next"))IntentSanitizer.Builder().allowComponent(...).allowData(...).build().sanitizeByThrowing(nested), or a PendingIntent you created
Reading typed extrasUntyped getParcelableExtra(key) then a castgetParcelableExtra(key, Foo::class.java) and getParcelableArrayListExtra(key, Foo::class.java) on API 33 and higher (IntentCompat for older)
Checking the callerTrusting getCallingActivity(), which a malicious caller can make nullSignature-level permissions; checkCallingPermission() with its integer result compared to PERMISSION_GRANTED
Web linksCustom scheme or unverified https filter<intent-filter android:autoVerify="true"> with assetlinks.json on each host
Sharing files<root-path>, path=".", or <external-path> for sensitive dataNarrow <files-path> or <cache-path> entries, exported="false", grant FLAG_GRANT_READ_URI_PERMISSION only
Provider queriesSelection strings built from caller inputProjection map with setStrictColumns(true), selectionArgs, one permission level per database

Intent redirection

Android's intent redirection guidance describes the attack: a vulnerable app unparcels an Intent supplied by another app and launches it with its own identity, which reaches unexported components such as private ContentProviders. Avoid exposing redirection at all. Where it is a feature, strip or check FLAG_GRANT_READ_URI_PERMISSION, FLAG_GRANT_WRITE_URI_PERMISSION, FLAG_GRANT_PERSISTABLE_URI_PERMISSION and FLAG_GRANT_PREFIX_URI_PERMISSION, confirm the resolved ComponentName is on an allowlist (handling a null result from resolveActivity), or use IntentSanitizer from androidx.core.content. Turn on StrictMode's detectUnsafeIntentLaunch() in debug builds for apps targeting API 31 and higher: it raises a violation when a nested Intent is unparcelled and immediately launched. Android 16 hardens this by default; Intent.removeLaunchSecurityProtection() disables the protection per Intent and should be treated as a code review red flag.

Deep links

Multiple apps can register the same URI, so a custom scheme can be hijacked (MITRE ATT&CK for Mobile records this as T1635.001 URI Hijacking). Since Android 12, an app must be verified for a domain, through Android App Links or the user's choice, before it handles that domain's web links. In code, treat every path segment and query parameter as untrusted: compare against an allowlist, and check that the user is authenticated and authorised before the deep link triggers any state change. Never let a deep link parameter choose a URL to load in a WebView or a component to launch. See the OAuth 2.0 and OpenID Connect Guide for redirect URI handling in mobile sign-in flows.

Input handling: SQL, archives, deserialisation and WebView

  • SQL: use ? placeholders with selectionArgs in rawQuery() and SQLiteDatabase.query(), or Room, whose @Query parameters are bound and whose SQL is verified at compile time. When a ContentProvider exposes a query interface, configure SQLiteQueryBuilder with setStrict(true), setStrictColumns(true) and setStrictGrammar(true). Do not let several providers share one SQLite file, because an injection in one reaches every table. See the SQL Injection Prevention Guide.
  • Archives: java.util.zip does not validate entry names, so an entry containing ../ writes outside the destination (ZipSlip). Resolve File(dest, entry.name).canonicalPath and require it to start with dest.canonicalPath + File.separator, otherwise throw ZipException. Extract only into an empty directory writable solely by the app, and apply the same check to TAR and other formats and to any third-party extraction library. See the Path Traversal Guide.
  • Deserialisation: every extra in an Intent's Bundle is deserialised, including ones you did not ask for. Avoid Java serialisation of untrusted data; if ObjectInputStream is unavoidable, use a look-ahead subclass that overrides resolveClass with an explicit allowlist, and make classes that must never be deserialised throw from readObject. Use the typed Parcel.readParcelable(loader, Foo::class.java) overload. Prefer plain data formats decoded into specific Kotlin classes over polymorphic decoding of arbitrary types. See the Secure Deserialisation Guide.
  • WebView: set allowFileAccess, allowFileAccessFromFileURLs, allowUniversalAccessFromFileURLs and allowContentAccess to false explicitly, because allowFileAccess defaulted to true up to API 29. Serve bundled content through WebViewAssetLoader at https://appassets.androidplatform.net rather than file:// URLs. Keep javaScriptEnabled false unless the page needs it, and expose addJavascriptInterface() only to content you ship or fully control.
WebSettings methodDefaultSecure coding value
setAllowFileAccesstrue on API 29 and lower, false on API 30 and higherfalse, set explicitly
setAllowFileAccessFromFileURLsfalse from API 16, deprecated in API 30false, set explicitly
setAllowUniversalAccessFromFileURLsfalse from API 16, deprecated in API 30false, set explicitly
setAllowContentAccesstruefalse unless content:// loading is required
setJavaScriptEnabledfalsetrue only for trusted, ideally bundled, content

Network code in Kotlin

Network Security Configuration should carry the TLS policy, and the Android App Security Guide covers its syntax. The code-level rule is simpler: never weaken validation in Kotlin. The recurring finding is a custom X509TrustManager whose checkServerTrusted() does nothing, or a HostnameVerifier that returns true, added to get past a staging certificate and then shipped. Ban both with a custom lint rule or a static analysis query, and use <debug-overrides> for test CAs so they only apply to debuggable builds. Keep cleartext off, put pins in the configuration file with a backup pin and an expiration date rather than in hand-written OkHttp code, and send tokens only in headers, never in URLs that end up in logs. Interception of mobile traffic is tracked in ATT&CK for Mobile as T1638 Adversary-in-the-Middle. See the How TLS Works Guide.

Authentication and session code

  • Credential Manager first: the Jetpack Credential Manager API handles passkeys, passwords, federated sign-in and digital credentials, and Android positions it as the replacement for legacy Google Sign-In, One Tap, Smart Lock for Passwords and local FIDO2 credentials. Migrating removes several bespoke credential code paths at once. See the Passwordless and Passkeys Guide.
  • Biometrics bound to keys: a BiometricPrompt success callback on its own is a Boolean that instrumentation can fake. For anything that unlocks a token or authorises a transaction, create the Keystore key with setUserAuthenticationParameters() and pass a CryptoObject to BiometricPrompt, so the cryptographic operation cannot happen without the authentication.
  • Authorisation on the server: a hidden button or a role flag in a ViewModel is not access control. Every privileged action must be authorised by the backend against the session, and the app should hold only short-lived access tokens plus a refresh token in Keystore-encrypted storage.
  • No long-lived machine credentials: cloud keys, payment provider secret keys and third-party API secrets must never be in the app. Use a backend that exchanges an attested app session for a narrow, short-lived token. See the API Keys vs OAuth Tokens Guide.

Build, dependencies and release gates

A Gradle build pulls hundreds of artefacts, and Android's own SDKs and third-party libraries run with your app's permissions. Gradle dependency verification reads gradle/verification-metadata.xml and switches on automatically when the file exists. Bootstrap it with ./gradlew --write-verification-metadata sha256, then review the result, because bootstrapping trusts whatever the repositories currently serve. Checksums prove integrity; signatures prove who published the artefact, so use both where publishers sign. Keep verification in the default strict mode, which fails the build before a mismatched artefact is used; lenient mode reports without failing and belongs only in a time-boxed migration. See the SBOM Guide.

  • Release build type: isMinifyEnabled = true so R8 shrinks, obfuscates and strips logging, no debuggable flag, and no test endpoints or feature flags that bypass authentication compiled into release.
  • Lint and static analysis as gates: fail the release build on Android lint security checks (for example exported components without permissions and unspecified PendingIntent mutability), plus your own rules for TrustManager overrides, Log calls with non-constant arguments and Intent forwarding.
  • Secret scanning: scan the repository and the built APK or AAB for keys before release; the APK is what attackers read. See the Git Secret Scanning Guide.

Choosing controls by app and team size

SituationMinimum secure coding baselineAdd when risk or scale grows
Small team, content or utility appExported audit, Room or bound queries, no embedded secrets, R8 with log strippingDependency verification once the team adds third-party SDKs
App with accounts and personal dataCredential Manager, Keystore-encrypted tokens, WebView hardening, deep link validationCryptoObject-bound biometrics, custom lint rules, MASVS L1 testing
Banking, health or paymentsAll of the above plus strict dependency verification and per-release secret scanning of the binaryMASVS L2 testing, attestation-gated token exchange, independent code review of IPC and crypto
Large organisation, many appsShared secure coding library (sanitisers, crypto wrapper, safe WebView factory)Central lint rule set and metrics across all repositories

Rolling out a Kotlin secure coding standard

  1. Inventory: list every exported component, deep link, ContentProvider, FileProvider path, WebView and archive or deserialisation call. Most teams find forgotten debug activities here.
  2. Fix the critical patterns: remove embedded secrets and rotate them, replace string-built SQL, add canonical path checks and remove any accept-all TrustManager. Rotation comes first because a removed secret remains valid in every old APK.
  3. Introduce shared helpers: one crypto wrapper over Keystore, one WebView factory with safe settings, one Intent sanitiser policy. Developers then call the safe option by default.
  4. Add gates in warning mode: run custom lint rules, secret scanning and lenient dependency verification on pull requests for two to four weeks, measuring findings without blocking.
  5. Enforce: switch rules to errors and verification to strict on the release branch. Roll back by reverting the rule configuration, not by suppressing findings inline, and record every suppression with an owner and expiry.
  6. Test in rings: ship to internal testers and a staged Play rollout percentage, watching crash rates for breakage from stricter WebView, Intent or deserialisation handling before full release.

Detection and measurement

  • Embedded secrets per release: count of keys found by scanning the built APK or AAB; target zero, with any finding blocking release.
  • Exported surface: number of exported components without a signature permission; track it per release and require a review for any increase.
  • Security lint debt: open security lint and static analysis findings, and the number of suppressions older than their expiry.
  • Dependency verification coverage: share of modules building in strict mode, and time to review a changed checksum.
  • Logging hygiene: PII or tokens detected in crash reports and analytics payloads, sampled each release.
  • Server-side signals: requests rejected for invalid tokens or failed attestation, and deep link calls that fail validation, which show probing in production.

Framework mapping

FrameworkReferenceKotlin and Android coding practice
NIST SP 800-53 Rev. 5SA-15 Development Process, Standards, and Tools; SA-11 Developer Testing and EvaluationSecure coding standard, lint gates, MASVS-based testing
NIST SP 800-53 Rev. 5SI-10 Information Input ValidationIntent, deep link, SQL, archive and WebView input validation
NIST SP 800-53 Rev. 5SC-12 Cryptographic Key Establishment and Management; SC-28 Protection of Information at Rest; IA-5 Authenticator ManagementKeystore keys, encrypted token storage, no embedded credentials
NIST SP 800-53 Rev. 5SC-8 Transmission Confidentiality and Integrity; SR-3 Supply Chain Controls and ProcessesNo weakened TLS validation; Gradle dependency verification
NIST CSF 2.0PR.PS-06; PR.DS-01; PR.DS-02Secure development practices; data at rest and in transit
MITRE ATT&CK for MobileT1409 Stored Application Data; T1635.001 URI Hijacking; T1638 Adversary-in-the-MiddleStorage, deep link and network controls above
OWASP MASVSMASVS-STORAGE, CRYPTO, AUTH, NETWORK, PLATFORM, CODE, RESILIENCE, PRIVACYVerification categories for each section of this guide

Common failure patterns

  • Cloud keys compiled into the app: Symantec found 1,859 Android and iOS apps with hard-coded AWS credentials, 77% of them valid, many arriving through shared SDKs the app developers had not examined; see the Mobile Apps Hard-Coded AWS Keys 2022 analysis.
  • Open backend behind a client-only check: the app enforces access while the database accepts anyone with its URL, as in the Firebase Misconfigurations 2024 exposure. Server rules, not Kotlin code, must enforce authorisation.
  • A "temporary" trust-all TrustManager: added for a staging server and never removed, it disables certificate validation for every user.
  • Trampoline activities: an exported activity that forwards whatever Intent it receives, turning every private component into a public one.
  • Data classes in logs: a session or user data class passed to a logger or crash reporter prints its tokens through the generated toString().
  • Unzipping updates or content packs without path checks: a crafted archive overwrites app files, including native libraries, leading to code execution.

Lessons from incidents

The Symantec findings and the iOS Apps Leaking Hard-Coded Secrets 2025 research make the same point from both platforms: secrets shipped in mobile binaries are routinely extracted at scale, store review does not catch them, and revoking them breaks installed versions. Design for that from the first release: the app proves who it is to your backend, and the backend issues narrow, short-lived credentials. These are non-human identities and deserve the same lifecycle as any other; see the OWASP NHI Top 10 NHI1 Improper Offboarding Guide for retiring credentials that outlive their purpose.

Practitioner checklist

  • Search the codebase and built APK for API keys, cloud credentials and private keys; rotate anything found before removing it.
  • Set android:exported explicitly on every component and review every exported one for a signature permission.
  • Replace any code that launches an Intent taken from extras with IntentSanitizer or a PendingIntent; enable detectUnsafeIntentLaunch() in debug.
  • Confirm all SQL uses bound parameters, Room or a strict SQLiteQueryBuilder.
  • Add canonical path checks to every archive extraction and file write derived from external names.
  • Set WebView file and content access flags to false explicitly and serve local content through WebViewAssetLoader.
  • Override toString() on data classes holding secrets or PII, and strip android.util.Log calls with R8 in release.
  • Bind biometric unlock to a Keystore key through CryptoObject, and move sign-in to Credential Manager.
  • Commit gradle/verification-metadata.xml, review it, and keep verification strict on release builds.
  • Track the six metrics above per release and review increases at the release gate.

Standards and references

Related NHI Mgmt Group resources: Android App Security Guide · Swift and iOS Secure Coding Guide · Mobile App Security Testing Guide · Secure Software Development Lifecycle (SSDLC) Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 26 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.