是否可以使用 HSM 保护 Android KeyChain?

Is it possible to secure the Android KeyChain with an HSM?

出于安全原因,我想将我的私钥存储在 HSM 中,然后通过 KeyChain. The KeyStore 提及它可以由 HSM 支持,但我没有找到任何说明可以使用 KeyChain.

的文档

基于 the KeyChain documentation,KeyChain 是在应用程序之间共享的正确方式:

Use the KeyChain API when you want system-wide credentials. When an app requests the use of any credential through the KeyChain API, users get to choose, through a system-provided UI, which of the installed credentials an app can access. This allows several apps to use the same set of credentials with user consent.

那么,是否可以使用 HSM 保护 Android KeyChain?

经过多方查找,终于找到答案是肯定的,是可以的。

Android 4.3 changelog 似乎是唯一记录它的地方:

Android also now supports hardware-backed storage for your KeyChain credentials, providing more security by making the keys unavailable for extraction. That is, once keys are in a hardware-backed key store (Secure Element, TPM, or TrustZone), they can be used for cryptographic operations but the private key material cannot be exported. Even the OS kernel cannot access this key material.


我用代码对此进行了测试,似乎一旦将 KeyPair 导入 KeyChain,它就会自动放入安全硬件中。这是我 运行 测试的 Kotlin 代码:

GlobalScope.launch {
    context?.let { it1 ->
        val privKey = KeyChain.getPrivateKey(it1, "device_certificate")
        Log.d("App", privKey.toString()) // Shows that this is an AndroidKeyStoreRSAPrivateKey
        val keyFactory: KeyFactory = KeyFactory.getInstance(privKey?.algorithm, "AndroidKeyStore")
        val keyInfo: KeyInfo = keyFactory.getKeySpec(privKey, KeyInfo::class.java)
        if (keyInfo.isInsideSecureHardware()) {
            Log.d("App", "The key is in secure hardware!")
        }
        else {
            Log.d("App", "The key is not in secure hardware!")
        }
    }
}

打印出“密钥在安全硬件中!”。