无法使用导入到 AndroidKeyStore RSA 私钥进行签名

Can't sign with imported to AndroidKeyStore RSA Private key

我正在尝试使用导入的密钥库密钥对一段数据进行签名:

我的密钥首先在 AndroidKeyStore 之外生成(这是故意的) 然后导入到AndroidKeyStore

使用以下方式:

    val keyGen = KeyPairGenerator.getInstance("RSA")
    keyGen.initialize(2048)
    val keyPair = keyGen.generateKeyPair()

    val keyProtectionSign = KeyProtection.Builder(KeyProperties.PURPOSE_SIGN or //
            KeyProperties.PURPOSE_VERIFY).setDigests(KeyProperties.DIGEST_SHA256) //

            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) //
            .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
            .build()
    keyStore.setEntry(signatureAlias,
            KeyStore.PrivateKeyEntry(keyPair.private, arrayOf(certificate)),
            keyProtectionSign)

之后我尝试使用密钥进行签名:

val keyStore = KeyStore.getInstance("AndroidKeyStore")
    keyStore.load(null)
    val privateKey = keyStore.getKey(signatureAlias,null)
    val signature = Signature.getInstance("SHA256withRSA")
    signature.initSign(privateKey)
    signature.update(data)
    val sign = signature.sign()

然而,行 signature.initSign(privateKey) 抛出异常:java.security.InvalidKeyException: Supplied key (android.security.keystore.AndroidKeyStoreRSAPrivateKey) is not a RSAPrivateKey instance

如果我不将密钥导入 android 密钥库,并尝试用它签名,它就可以工作。

如果我直接在 AndroidKeyStore 中生成密钥,它也会失败并出现同样的错误。

我的代码有什么问题?为什么我不能用我的 RSA 密钥签名?

尝试查看此线程中讨论的问题:

https://markmail.org/message/4omngfbqzdq3wk3b#query:+page:1+mid:ne47xbhggf6samib+state:results

Unfortunately, Bouncy Castle JCA Provider has a bug (http://www.bouncycastle.org/jira/browse/BJA-543 https://www.google.com/url?q=http://www.bouncycastle.org/jira/browse/BJA-543&sa=D&usg=AFQjCNEErNOODYZHHZomGgR1y7NLq2yegw) where is advertises to JCA that it can handle any keys, even those that it actually can't handle

...

If you must install the Bouncy Castle JCA Provider, install it below Android Keystore JCA provider. The best way to achieve that is to find the index at which the platform-bundled Bouncy Castle provider is installed, and then invoke Security.insertProviderAt with that same index and your Bouncy Castle Provider.