我想在我的 Android 设备上生成一个密钥对,该密钥对具有作为 Google 硬件证明根证书的根证书。
我在Android的文档中here看到我可以更改自签名证书
对于非对称密钥对,还将生成自签名 X.509 证书并将其存储在 Android 密钥库中。这是因为 KeyStore 抽象不支持存储没有证书的密钥对。证书的主题、序列号和有效期可以在此规范中自定义。自签名证书稍后可能会被证书颁发机构 (CA) 签名的证书替换。
我可以看到 here 我可以使用 keyStore 获取与硬件支持的密钥库关联的 X.509 证书链
getCertificateChain()
使用 KeyStore 对象的
方法获取对与硬件支持的密钥库关联的 X.509 证书链的引用。getCertificateChain()
但是,我还没有找到如何使用 Google 硬件证明根证书
更改密钥对上的证书private fun generateKeyPairAttestationAndGetPublicKey(): String {
val keyStore = KeyStore.getInstance("AndroidKeyStore")
val keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"
)
keyPairGenerator.initialize(
KeyGenParameterSpec.Builder(
"my-mobile-key",
KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_ENCRYPT
)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.build()
)
keyPairGenerator.generateKeyPair()
keyStore.load(null)
val keyEntry = keyStore.getEntry("my-mobile-key", null) as KeyStore.PrivateKeyEntry
val x509Cert = keyEntry.certificate as? X509Certificate ?: throw Exception("Certificate generated by the KeyPair is not a X509Certificate")
}
我怎样才能做到这一点?
private fun generateNewKeyPairWithDifferentRootCertificate(): String {
val keyStore = KeyStore.getInstance("AndroidKeyStore")
val keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"
)
keyPairGenerator.initialize(
KeyGenParameterSpec.Builder(
"new-mobile-key", // Use a different alias
KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_ENCRYPT
)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.build()
)
keyPairGenerator.generateKeyPair()
// code to retrieve the public key
}
您是对的,在 Android 密钥库中生成非对称密钥对时,它会自动为该密钥对创建自签名证书。要将其替换为链接到 Google 硬件证明根的证书,您需要:
生成密钥对,就像您在代码片段中一样。
获取生成的私钥的证书签名请求(CSR):
val privKey = (keyEntry.privateKey as PrivateKey)
val csr = PKCS10CertificationRequest(
"CN=my-mobile-key",
privKey,
AlgorithmId.SHA256_WITH_RSA_ENCRYPTION
)
val csrBytes = csr.encoded
将 CSR 发送到您的 Google Cloud 帐户或第三方 CA 进行签名。他们将返回链接到硬件证明根的证书。
将签名的证书链导入Keystore:
val signedCert = // certificate chain signed by Google CA
val certEntry = KeyStore.TrustedCertificateEntry(signedCert)
keyStore.setEntry("my-mobile-key", certEntry, null)
现在,当您检索该条目时,它将包含 Google 签名的证书,而不是自签名的证书。
关键部分是获取生成的密钥对的 CSR,并用 Google 签名的证书替换自签名的证书。让我知道这是否有助于解释该过程!