DEV Community

Cover image for One Codebase, Two Attack Surfaces: A Practical Guide to Securing Kotlin Multiplatform Apps
Padmakar Garg
Padmakar Garg

Posted on Edited on

One Codebase, Two Attack Surfaces: A Practical Guide to Securing Kotlin Multiplatform Apps

Short answer: Kotlin Multiplatform shares your logic, not your security. Keep decisions and flows in commonMain, and put keys, secure storage, TLS pinning and attestation in platform code (Android Keystore, iOS Keychain, Play Integrity, App Attest), with your server as the final judge.

I'm Padmakar Garg, a Senior Android Developer. I work on secure messaging, encrypted calling and Android security. The code below is for understanding where each protection belongs. For production, use vetted, maintained libraries (see the end).

Update: a reader pointed out that my first version of SecureStorage returned null for every failure, so common code couldn't tell "no value" from "the key was invalidated". I've fixed that below. See "Handling invalidated keys".

Kotlin Multiplatform lets you share business logic between Android and iOS. That's a huge productivity win, but it creates a quiet security trap: shared code runs on two very different platforms, each with its own attack surface.

A token stored in plain text is exposed on both. A hardcoded key in commonMain ships in both binaries. And the strongest protections (hardware-backed keys, attestation) live in the platform layer, not in shared Kotlin.

This article shows how to structure a KMP app so security-sensitive work happens in the right place.

The core idea: share logic, delegate trust to the platform

A good rule for KMP security:

Put decisions and flows in commonMain. Put secrets, keys and trust anchors behind expect/actual or interfaces implemented by each platform.

Shared code should never touch raw key material or decide "is this device trustworthy?" by itself. It should call a platform capability and act on the result.

1. Secure storage: Keystore and Keychain behind one interface

Don't store tokens in plain SharedPreferences, NSUserDefaults or a settings library without encryption. Define a small contract in common code.

The important design choice: don't return String?. A bare null can't distinguish "nothing stored" from "the key is gone" from "the device is temporarily locked", and each of those needs a different reaction. Return an explicit result instead:

// commonMain
enum class SecureStatus {
    OK,               // operation succeeded
    NOT_FOUND,        // nothing stored under this key
    KEY_INVALIDATED,  // the key or data can never be read again: wipe and re-enroll
    FAILURE           // transient or unknown error: don't wipe, retry later
}

data class SecureResult(
    val status: SecureStatus,
    val value: String? = null
)

interface SecureStorage {
    fun put(key: String, value: String): SecureResult
    fun get(key: String): SecureResult
    fun remove(key: String)
    fun clearAll()   // delete stored data AND the platform key
}
Enter fullscreen mode Exit fullscreen mode

I use a flat result type instead of a generic sealed class because it maps cleanly to Swift, which matters when the iOS side implements the interface.

Android: AES-GCM with a key in Android Keystore

// androidMain
class AndroidSecureStorage(context: Context) : SecureStorage {

    private val prefs = context.getSharedPreferences("secure_store", Context.MODE_PRIVATE)
    private val alias = "app_master_key"

    private fun secretKey(): SecretKey {
        val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
        (ks.getKey(alias, null) as? SecretKey)?.let { return it }

        val generator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"
        )
        generator.init(
            KeyGenParameterSpec.Builder(
                alias,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            )
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setKeySize(256)
                .build()
        )
        return generator.generateKey()
    }

    override fun put(key: String, value: String): SecureResult = try {
        val cipher = Cipher.getInstance("AES/GCM/NoPadding")
        cipher.init(Cipher.ENCRYPT_MODE, secretKey())
        val blob = cipher.iv + cipher.doFinal(value.toByteArray())
        prefs.edit().putString(key, Base64.encodeToString(blob, Base64.NO_WRAP)).apply()
        SecureResult(SecureStatus.OK)
    } catch (e: KeyPermanentlyInvalidatedException) {
        SecureResult(SecureStatus.KEY_INVALIDATED)
    } catch (e: Exception) {
        SecureResult(SecureStatus.FAILURE)
    }

    override fun get(key: String): SecureResult {
        val encoded = prefs.getString(key, null)
            ?: return SecureResult(SecureStatus.NOT_FOUND)
        return try {
            val blob = Base64.decode(encoded, Base64.NO_WRAP)
            val iv = blob.copyOfRange(0, 12)
            val cipherText = blob.copyOfRange(12, blob.size)
            val cipher = Cipher.getInstance("AES/GCM/NoPadding")
            cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, iv))
            SecureResult(SecureStatus.OK, String(cipher.doFinal(cipherText)))
        } catch (e: KeyPermanentlyInvalidatedException) {
            SecureResult(SecureStatus.KEY_INVALIDATED)   // key was invalidated
        } catch (e: UnrecoverableKeyException) {
            SecureResult(SecureStatus.KEY_INVALIDATED)   // key can't be used any more
        } catch (e: AEADBadTagException) {
            SecureResult(SecureStatus.KEY_INVALIDATED)   // wrong key, or corrupted/tampered blob
        } catch (e: Exception) {
            SecureResult(SecureStatus.FAILURE)           // transient or unknown
        }
    }

    override fun remove(key: String) { prefs.edit().remove(key).apply() }

    override fun clearAll() {
        prefs.edit().clear().apply()
        runCatching {
            KeyStore.getInstance("AndroidKeyStore")
                .apply { load(null) }
                .deleteEntry(alias)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The key never leaves the Keystore. Only the encrypted blob is stored.

iOS: Keychain

Writing Keychain code in Kotlin/Native means verbose cinterop with CFDictionary. A clean alternative is to implement the interface in Swift and inject it from the iOS app:

// iosApp
final class IosSecureStorage: NSObject, SecureStorage {
    private let service = "com.example.app"

    private func baseQuery(_ key: String) -> [String: Any] {
        [kSecClass as String: kSecClassGenericPassword,
         kSecAttrService as String: service,
         kSecAttrAccount as String: key]
    }

    func put(key: String, value: String) -> SecureResult {
        SecItemDelete(baseQuery(key) as CFDictionary)
        var query = baseQuery(key)
        query[kSecValueData as String] = Data(value.utf8)
        query[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
        let status = SecItemAdd(query as CFDictionary, nil)
        return SecureResult(status: status == errSecSuccess ? .ok : .failure, value: nil)
    }

    func get(key: String) -> SecureResult {
        var query = baseQuery(key)
        query[kSecReturnData as String] = true
        query[kSecMatchLimit as String] = kSecMatchLimitOne
        var result: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &result)

        switch status {
        case errSecSuccess:
            guard let data = result as? Data,
                  let text = String(data: data, encoding: .utf8) else {
                return SecureResult(status: .failure, value: nil)
            }
            return SecureResult(status: .ok, value: text)
        case errSecItemNotFound:
            return SecureResult(status: .notFound, value: nil)
        case errSecInteractionNotAllowed:
            // Device is locked: temporary. Do NOT wipe, retry later.
            return SecureResult(status: .failure, value: nil)
        default:
            return SecureResult(status: .failure, value: nil)
        }
    }

    func remove(key: String) { SecItemDelete(baseQuery(key) as CFDictionary) }

    func clearAll() {
        let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
                                    kSecAttrService as String: service]
        SecItemDelete(query as CFDictionary)
    }
}
Enter fullscreen mode Exit fullscreen mode

WhenUnlockedThisDeviceOnly keeps items off backups and other devices. (Check the generated Kotlin/Native header for the exact Swift names of the enum cases in your project.)

Prefer a library? Several KMP libraries wrap Keystore and Keychain behind one API, for example KSafe and SecureVault KMP. Review their security notes and maintenance activity before adopting one in production.

Handling invalidated keys

Hardware-backed keys can disappear or become unusable while your encrypted data is still sitting in storage. Common cases:

  • Auth-bound keys on Android. If you create the key with setUserAuthenticationRequired(true) (for example to gate access with biometrics), Android can invalidate it when the secure lock screen is removed or changed, or when new biometrics are enrolled. Using it then throws KeyPermanentlyInvalidatedException. The key in the example above is not auth-bound, so these events don't affect it.
  • Backup restore or device migration. The encrypted preferences come back on the new device, but the Keystore key does not. Decryption then fails, typically with AEADBadTagException.
  • Corrupted or tampered data. GCM authentication fails, so the blob can never be decrypted.
  • iOS. Items protected with an access control such as .biometryCurrentSet stop being usable when the biometric enrollment changes. Treat that as KEY_INVALIDATED too.

If you want biometric-bound keys on Android, add this when building the key:

KeyGenParameterSpec.Builder(alias, PURPOSE_ENCRYPT or PURPOSE_DECRYPT)
    // ...
    .setUserAuthenticationRequired(true)
    .setInvalidatedByBiometricEnrollment(true)   // API 24+
    .build()
Enter fullscreen mode Exit fullscreen mode

The reaction belongs in commonMain, because it's a decision, not a platform detail:

// commonMain
sealed interface SessionState {
    data class Restored(val refreshToken: String) : SessionState
    data object SignedOut : SessionState
    data object ReEnrollRequired : SessionState
    data object RetryLater : SessionState
}

fun restoreSession(storage: SecureStorage): SessionState {
    val result = storage.get("refresh_token")
    return when (result.status) {
        SecureStatus.OK -> SessionState.Restored(requireNotNull(result.value))
        SecureStatus.NOT_FOUND -> SessionState.SignedOut
        SecureStatus.KEY_INVALIDATED -> {
            storage.clearAll()                   // delete stale data and the dead key
            SessionState.ReEnrollRequired        // fresh sign-in / re-enrollment
        }
        SecureStatus.FAILURE -> SessionState.RetryLater   // don't wipe on transient errors
    }
}
Enter fullscreen mode Exit fullscreen mode

Three rules I follow:

  1. Wipe on KEY_INVALIDATED, never on FAILURE. A locked phone or a temporary error shouldn't log the user out.
  2. Never silently regenerate the key and carry on. That hides the event from the user and the backend. Force a fresh sign-in, and revoke the old session server-side.
  3. Make the failure visible in telemetry (without logging secrets), so you can see how often it happens.

2. Network security: pin certificates per engine

Ktor is the usual KMP HTTP client, and it uses a different engine on each platform. TLS pinning therefore happens in the platform engine, not in common code.

// commonMain
expect fun createHttpClient(): HttpClient
Enter fullscreen mode Exit fullscreen mode
// androidMain (OkHttp engine)
actual fun createHttpClient() = HttpClient(OkHttp) {
    engine {
        config {
            certificatePinner(
                CertificatePinner.Builder()
                    .add("api.example.com", "sha256/PRIMARY_PIN_BASE64=")
                    .add("api.example.com", "sha256/BACKUP_PIN_BASE64=")
                    .build()
            )
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
// iosMain (Darwin engine)
actual fun createHttpClient() = HttpClient(Darwin) {
    engine {
        handleChallenge(
            CertificatePinner.Builder()
                .add("api.example.com", "sha256/PRIMARY_PIN_BASE64=")
                .add("api.example.com", "sha256/BACKUP_PIN_BASE64=")
                .build()
        )
    }
}
Enter fullscreen mode Exit fullscreen mode

(Check the Ktor docs for the exact Darwin pinning API in your Ktor version.)

Pinning tips:

  • Pin the public key (SPKI), not the whole certificate, so renewals don't break the app.
  • Always ship a backup pin, or a certificate rotation can lock every user out.
  • Plan how you'll update pins (remote config or a forced-update path).

3. Cryptography: don't write your own

Avoid hand-rolling crypto in common code. Two safe patterns:

  1. Use platform primitives (Keystore/CryptoKit) through expect/actual, as above.
  2. Use a well-reviewed multiplatform crypto library, such as cryptography-kotlin, which wraps each platform's native provider.

Whichever you choose: use AES-GCM (authenticated encryption), a fresh random IV/nonce for every encryption, and never reuse a nonce with the same key.

4. Secrets in commonMain are secrets in both apps

Anything compiled into your binary can be extracted: API keys, signing secrets, "hidden" endpoints. Moving it to commonMain doesn't hide it. Instead:

  • Keep long-lived secrets on your backend and issue short-lived tokens to the app.
  • Don't commit keys. Inject per-build values from CI.
  • Enable R8/ProGuard for the Android release build. Kotlin/Native iOS binaries are still reverse-engineerable, so never rely on obscurity.

5. Device and app integrity: attestation per platform

"Is this device and app genuine?" can't be answered safely in shared code. Define the contract, implement it natively, and verify on your server:

// commonMain
interface IntegrityProvider {
    /** Returns a token your backend verifies. Nonce must come from the server. */
    suspend fun attest(serverNonce: String): Result<String>
}
Enter fullscreen mode Exit fullscreen mode
  • Android: implement with the Play Integrity API.
  • iOS: implement with App Attest (DeviceCheck).

The shared flow stays identical: request a nonce from the server, get a token from the platform, send it back, and let the backend decide what the user may do. Never trust a verdict decided only on the device.

6. Smaller things that matter

  • Logging: never log tokens, passwords or PII. Strip or silence verbose logging in release builds.
  • Screens: on Android use FLAG_SECURE for sensitive screens; on iOS hide content when the app moves to the background (app switcher snapshots).
  • Biometrics: use them to unlock access to a key (Keystore/Keychain access control), not just as a UI gate that can be skipped. Remember that auth-bound keys can be invalidated, so handle it as shown above.
  • Dependencies: KMP pulls in many libraries. Pin versions and watch for security advisories.

Common mistakes

  • Treating shared code as "secure by default".
  • Returning String? from secure storage and swallowing every exception into null, so "missing" and "invalidated" look identical.
  • Wiping data on a transient error (for example a locked device) instead of only on a permanent one.
  • Silently regenerating a lost key instead of forcing re-enrollment.
  • One pinned certificate with no backup pin.
  • Storing refresh tokens in unencrypted multiplatform settings.
  • Trusting a root/jailbreak check result without server verification.
  • Putting authorization rules (prices, roles, limits) in the client.

What to use in production

The snippets above show the shape of a secure KMP setup, but writing your own security layer is risky because small mistakes are invisible and expensive. For a real app, prefer:

  • Platform-native storage (Android Keystore and iOS Keychain), or a maintained KMP wrapper around them.
  • A vetted crypto library (platform providers or a reviewed multiplatform library) instead of custom code.
  • Server-verified attestation (Play Integrity on Android, App Attest on iOS) for device and app trust.

Use this article to understand where each protection belongs, not to replace tested libraries. If you want to see a crypto protocol implemented from a specification in Kotlin, I've published an SDK implementing MTProto 2.0 primitives (AES-IGE and Diffie-Hellman key exchange): github.com/gargpadmakar/MTProtoCrypto.

Summary

  1. Shared code is not secure by default. Each platform has its own attack surface.
  2. Keep flows and decisions in commonMain; keep keys and trust anchors in platform code.
  3. Store secrets with Android Keystore and iOS Keychain behind one common interface.
  4. Return an explicit result (OK, NOT_FOUND, KEY_INVALIDATED, FAILURE) instead of a nullable string, so common code can react correctly.
  5. Wipe and re-enroll on an invalidated key, and never on a transient failure.
  6. Pin TLS certificates per Ktor engine, and always ship a backup pin.
  7. Use AES-GCM with a fresh nonce every time, and never write your own crypto.
  8. Never ship long-lived secrets in the binary; use short-lived tokens from your backend.
  9. Verify device integrity on the server with Play Integrity and App Attest.

Related reading


About the author: Padmakar Garg is a Senior Android Developer with 8+ years of experience in Kotlin, Jetpack Compose, Kotlin Multiplatform and mobile security, building real-time encrypted messaging apps. Portfolio and blog: gargpadmakar.github.io. Connect on LinkedIn and GitHub.

Top comments (2)

Collapse
 
userxnom profile image
Abdullah Naseer •

The expect/actual split is the part I'd steal — decisions in commonMain, trust anchors in platform code. One gap I kept looking for: what happens when the Keystore key gets invalidated, for example when the user changes their lock screen or adds a fingerprint? On Android that throws KeyPermanentlyInvalidatedException and the stored blob is suddenly unreadable. Does your SecureStorage interface surface that as a distinct failure so the app can wipe and re-enroll, or does it just look like a missing value from common code?

Collapse
 
gargpadmakar profile image
Padmakar Garg •

Great catch, and you're right: in the article's code get() swallows every exception into null, so common code can't tell "no value" from "key gone". That's a real gap.

One nuance: the key in the article isn't auth-bound, so a lock screen or fingerprint change won't invalidate it. KeyPermanentlyInvalidatedException shows up once you add setUserAuthenticationRequired(true) (the biometric-gated setup from section 6). The other common case is a backup restore or device migration: the encrypted prefs come back but the Keystore key doesn't, so decryption fails with AEADBadTagException.

I'd surface it as a distinct result instead of String?:

// commonMain
sealed interface SecureReadResult {
    data class Success(val value: String) : SecureReadResult
    data object NotFound : SecureReadResult
    data object KeyInvalidated : SecureReadResult   // wipe + re-enroll
    data class Failure(val cause: Throwable?) : SecureReadResult // transient/unknown
}

interface SecureStorage {
    fun put(key: String, value: String)
    fun get(key: String): SecureReadResult
    fun remove(key: String)
    fun clearAll()
}
Enter fullscreen mode Exit fullscreen mode
// androidMain
override fun get(key: String): SecureReadResult {
    val encoded = prefs.getString(key, null) ?: return SecureReadResult.NotFound
    return try {
        // ... decode, init cipher, doFinal
        SecureReadResult.Success(String(plain))
    } catch (e: KeyPermanentlyInvalidatedException) {
        SecureReadResult.KeyInvalidated
    } catch (e: UnrecoverableKeyException) {
        SecureReadResult.KeyInvalidated
    } catch (e: AEADBadTagException) {
        SecureReadResult.KeyInvalidated   // wrong key, or corrupted/tampered blob
    } catch (e: Exception) {
        SecureReadResult.Failure(e)
    }
}
Enter fullscreen mode Exit fullscreen mode

Then the decision lives in commonMain: on KeyInvalidated, delete the alias and the stored blobs, clear the local session, and send the user through a fresh sign-in or re-enrollment (and revoke the old session server-side). The one thing I'd never do is silently regenerate the key and carry on, because that hides the event from both the user and the backend.

iOS has the same idea: errSecItemNotFound (missing) vs errSecInteractionNotAllowed (device locked, try later) vs auth failures, all mapped to distinct results.

I'll update the article with this. Thanks for the push!