KMP 的 expect/actual 封装 Keystore?

解读

面试官真正想考察的是:

  1. 你是否理解 Kotlin Multiplatform(KMP)“共享代码 + 平台实现” 的架构思想;
  2. 能否用 expect/actual 机制把 Android 的 AndroidKeystore、iOS 的 Keychain、桌面(JVM)的 KeyStore 统一成一套类型安全的 API;
  3. 是否能在不破坏 KMP 约束(如 commonMain 里不能出现平台类)的前提下,处理好异步、异常、密钥别名冲突、国密合规等国内工程落地细节。

一句话:不是问“怎么调用 Keystore”,而是问“怎么把三个平台的 Keystore 差异装进一个 KMP 模块,让上层业务无感知”。

知识点

  1. expect/actual 的编译期分发规则:common 声明 → 平台实现,actual 修饰符必须与 expect 完全匹配(包名可不同,但全限定名必须唯一)。
  2. common 层只能声明 Kotlin 标准库与 kotlin.xxx 官方 API,不能直接引用 java.security.、android.security.、Security.framework 等。
  3. 平台差异:
    Android:AndroidKeystore 是硬件级 TEE/SE,别名长度 ≤512 字节,支持国密算法需厂商实现,华为/小米/OPPO 机型需额外适配。
    iOS:Keychain 以 kSecAttrService + kSecAttrAccount 做联合主键,Group 共享需配置 Keychain Sharing Entitlement,国密需自行注入 CC 库。
    JVM:JKS/PKCS12 文件路径、密码、权限、FIPS 模式(国内金融项目需过国密 FIPS 140-2 三级)。
  4. 协程与线程:common 层用 suspend 声明,actual 实现里 Android/iOS 可切到 Dispatchers.IO,但不得把平台回调线程直接暴露给 common。
  5. 国内合规:密钥不得明文落盘,密钥别名建议带应用包名+用户 ID 哈希,避免多用户混用;国密 SM2/SM3/SM4 算法需通过硬件或商密库实现,并在隐私政策中声明。
  6. 异常映射:平台抛出的异常需包装成 common 层定义的 KeystoreException,避免在 iosMain 里直接抛出 NSError 导致 Swift 侧无法 catch。

答案

commonMain/Keystore.kt

expect class Keystore(alias: String) {
    @Throws(KeystoreException::class)
    suspend fun generateKeyPair()

    @Throws(KeystoreException::class)
    suspend fun sign(data: ByteArray): ByteArray

    @Throws(KeystoreException::class)
    suspend fun deleteEntry()
}

class KeystoreException(message: String, cause: Throwable? = null) : Exception(message, cause)

androidMain/Keystore.android.kt

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import java.security.KeyPairGenerator
import java.security.Signature
import java.security.KeyStore as AndroidKeyStore

actual class Keystore actual constructor(private val alias: String) {
    private val androidKeyStore = AndroidKeyStore.getInstance("AndroidKeyStore").apply { load(null) }

    actual suspend fun generateKeyPair() = withContext(Dispatchers.IO) {
        if (androidKeyStore.containsAlias(alias)) return@withContext
        val spec = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY)
            .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
            .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
            .setUserAuthenticationRequired(false) // 国内大多后台签名场景无需指纹
            .build()
        KeyPairGenerator.getInstance("RSA", "AndroidKeyStore").run {
            initialize(spec)
            generateKeyPair()
        }
    }

    actual suspend fun sign(data: ByteArray): ByteArray = withContext(Dispatchers.IO) {
        val entry = androidKeyStore.getEntry(alias, null) as? AndroidKeyStore.PrivateKeyEntry
            ?: throw KeystoreException("Key not found")
        Signature.getInstance("SHA256withRSA").run {
            initSign(entry.privateKey)
            update(data)
            sign()
        }
    }

    actual suspend fun deleteEntry() = withContext(Dispatchers.IO) {
        androidKeyStore.deleteEntry(alias)
    }
}

iosMain/Keystore.ios.kt

import kotlinx.cinterop.*
import platform.Security.*

actual class Keystore actual constructor(private val alias: String) {
    private val service = "kmp.${alias}"
    actual suspend fun generateKeyPair() {
        // 简化:如已存在直接返回
        if (queryPrivateKey() != null) return
        val tag = "kmp.$alias.private".cstr
        val publicTag = "kmp.$alias.public".cstr
        memScoped {
            val privateAttrs = mapOf(
                kSecAttrIsPermanent to CFBridgingRetain(true),
                kSecAttrApplicationTag to CFBridgingRetain(tag.ptr)
            )
            val publicAttrs = mapOf(
                kSecAttrIsPermanent to CFBridgingRetain(true),
                kSecAttrApplicationTag to CFBridgingRetain(publicTag.ptr)
            )
            val keyPairAttrs = mapOf(
                kSecAttrKeyType to kSecAttrKeyTypeRSA,
                kSecAttrKeySizeInBits to CFBridgingRetain(2048),
                kSecPrivateKeyAttrs to CFBridgingRetain(privateAttrs),
                kSecPublicKeyAttrs to CFBridgingRetain(publicAttrs)
            )
            val publicKeyPtr = alloc<SecKeyRefVar>()
            val privateKeyPtr = alloc<SecKeyRefVar>()
            val status = SecKeyGeneratePair(CFDictionaryCreateMutableFromMap(keyPairAttrs), publicKeyPtr.ptr, privateKeyPtr.ptr)
            if (status != errSecSuccess) throw KeystoreException("iOS Keychain generate failed: $status")
        }
    }

    actual suspend fun sign(data: ByteArray): ByteArray = memScoped {
        val key = queryPrivateKey() ?: throw KeystoreException("Key not found")
        val hash = SHA256.hash(data) // 自行实现或使用 CC_SHA256
        val signature = alloc<CFDataRefVar>()
        val status = SecKeyCreateSignature(key, kSecKeyAlgorithmRSASignatureMessagePKCS1SHA256, CFDataCreate(null, hash.refTo(0), hash.size.toLong()), signature.ptr)
        if (status != errSecSuccess) throw KeystoreException("Sign failed: $status")
        CFDataGetBytePtr(signature.value)!!.readBytes(CFDataGetLength(signature.value))
    }

    actual suspend fun deleteEntry() {
        val query = mapOf(
            kSecClass to kSecClassKey,
            kSecAttrApplicationTag to "kmp.$alias.private".cstr.ptr,
            kSecAttrKeyType to kSecAttrKeyTypeRSA
        )
        SecItemDelete(CFDictionaryCreateMutableFromMap(query))
    }

    private fun queryPrivateKey(): SecKeyRef? {
        val query = mapOf(
            kSecClass to kSecClassKey,
            kSecAttrApplicationTag to "kmp.$alias.private".cstr.ptr,
            kSecAttrKeyType to kSecAttrKeyTypeRSA,
            kSecReturnRef to kCFBooleanTrue
        )
        val result = alloc<CFTypeRefVar>()
        return if (SecItemCopyMatching(CFDictionaryCreateMutableFromMap(query), result.ptr) == errSecSuccess) result.value as SecKeyRef else null
    }
}

jvmMain/Keystore.jvm.kt

import java.security.KeyStore
import java.security.Signature
import java.io.File
import java.security.cert.Certificate
import javax.crypto.spec.SecretKeySpec

actual class Keystore actual constructor(private val alias: String) {
    private val keyStoreFile = File(System.getProperty("user.home"), ".kmp/keystore.p12")
    private val password = "changeit".toCharArray() // 国内生产环境应走环境变量或 KMS
    private val keyStore = KeyStore.getInstance("PKCS12").apply {
        if (!keyStoreFile.exists()) {
            load(null, password)
            store(keyStoreFile.outputStream(), password)
        } else {
            load(keyStoreFile.inputStream(), password)
        }
    }

    actual suspend fun generateKeyPair() = withContext(Dispatchers.IO) {
        if (keyStore.containsAlias(alias)) return@withContext
        val kp = java.security.KeyPairGenerator.getInstance("RSA").apply { initialize(2048) }.generateKeyPair()
        val cert = generateSelfSignedCert(kp) // 自行实现
        keyStore.setKeyEntry(alias, kp.private, password, arrayOf(cert))
        keyStore.store(keyStoreFile.outputStream(), password)
    }

    actual suspend fun sign(data: ByteArray): ByteArray = withContext(Dispatchers.IO) {
        val entry = keyStore.getKey(alias, password) as? java.security.PrivateKey ?: throw KeystoreException("Key not found")
        Signature.getInstance("SHA256withRSA").run {
            initSign(entry)
            update(data)
            sign()
        }
    }

    actual suspend fun deleteEntry() = withContext(Dispatchers.IO) {
        keyStore.deleteEntry(alias)
        keyStore.store(keyStoreFile.outputStream(), password)
    }
}

使用方(common 层):

suspend fun businessLogin(userId: String, challenge: ByteArray) {
    val ks = Keystore("user_${userId.sha256()}")
    ks.generateKeyPair()
    val signature = ks.sign(challenge)
    api.submitSignature(signature)
}

拓展思考

  1. 国密改造:
    在 Android 侧通过厂商商密 SDK(华为 HMS 密码套件、小米安全元件)生成 SM2 密钥对,iOS 侧需集成 GMObjC 或自行封装 Security.framework 的 SecKeyAlgorithm 扩展,JVM 侧加载 BouncyCastle 的 SM2 Provider;common 层再抽象一套 ExpectSignatureAlgorithm 枚举,通过 expect/actual 映射到平台算法。

  2. 多用户隔离:
    国内 App 普遍支持“应用分身”与“子用户”,密钥别名务必带 userId+processName 哈希,避免 Alias 冲突导致串号。

  3. 合规审计:
    金融类 App 过中国银联、央行备案时,需要输出《密钥生命周期管理文档》,expect/actual 模块需记录密钥生成、使用、销毁的日志,并提供 common 层统一接口供 SDK 调用方注入审计埋点。

  4. 性能优化:
    密钥生成是耗时操作,可在首次启动时后台协程预生成,Android 侧利用 WorkManager 保证进程被杀后重试;iOS 侧利用 BGTaskScheduler 在后台调度。

  5. 测试策略:
    在 commonTest 里使用 kotlin-test + Turbine 做协程流断言;androidInstrumentedTest 里通过 AndroidJUnit4 调用 expect/actual,验证硬件 TEE 通路;iOS 侧通过 XCTest 桥接 Kotlin/Native 框架,验证 Keychain Group 共享场景。