【发布时间】:2022-07-28 17:54:44
【问题描述】:
我正在尝试使用 AndroidKeyStore 通过客户端身份验证调用 API,但出现以下错误
W/CryptoUpcalls:找不到算法提供者:RSA/ECB/NoPadding
android.security.KeyStoreException: 填充模式不兼容
fun createSSLContextAndroid(context: Context): SSLContext? {
val certificateFactory = CertificateFactory.getInstance("X.509")
val caCertificate =
certificateFactory.generateCertificate(context.resources.openRawResource(R.raw.ca))
val clientCertificate = certificateFactory.generateCertificate(context.resources.openRawResource(R.raw.android_new))
val keyStoreType = KeyStore.getDefaultType()
val keyStoreTrust = KeyStore.getInstance(keyStoreType)
keyStoreTrust.load(null, null)
keyStoreTrust.setCertificateEntry("mt", caCertificate)
val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
val tmf = TrustManagerFactory.getInstance(tmfAlgorithm)
tmf.init(keyStoreTrust)
val ks = KeyStore.getInstance("AndroidKeyStore")
ks.load(null, null)
val certificateAlias = "certificate"
ks.setCertificateEntry(certificateAlias, clientCertificate)
val privateKeyEntry = ks.getEntry(Config.KEYSTORE_ALIAS, null) as KeyStore.PrivateKeyEntry
ks.setKeyEntry(Config.KEYSTORE_ALIAS, privateKeyEntry.privateKey, null, arrayOf(clientCertificate))
val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
kmf.init(ks, null)
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(kmf.keyManagers, tmf.trustManagers, null)
return sslContext
}
使用以下代码生成密钥
fun initKeyGeneratorPair(): KeyPairGenerator {
val kpg: KeyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_RSA,
"AndroidKeyStore"
)
kpg.initialize(
KeyGenParameterSpec.Builder(
Config.KEYSTORE_ALIAS,
KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY or KeyProperties.PURPOSE_ENCRYPT or
KeyProperties.PURPOSE_DECRYPT
)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.setDigests(
KeyProperties.DIGEST_NONE,
KeyProperties.DIGEST_SHA256,
KeyProperties.DIGEST_SHA512
)
.setKeySize(4096)
.build()
)
return kpg
}
【问题讨论】:
标签: android cryptography ssl-certificate keystore