【问题标题】:Getting error creating SSLContext KeyManagerFactory using AndroidKeyStore in API call在 API 调用中使用 AndroidKeyStore 创建 SSLContext KeyManagerFactory 时出错
【发布时间】: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


    【解决方案1】:

    我还没有发现这个问题的确切原因,但对我来说,通过添加.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) 来稍微改变一下KeyGenParameterSpec 是有帮助的。

    我仍在寻找确切的原因以及这是否是适当的解决方案。

    【讨论】:

      猜你喜欢
      • 2015-06-17
      • 2021-03-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      相关资源
      最近更新 更多