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

标签 android kotlin rsa signing android-keystore

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

我的 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)

之后,我尝试使用 key 进行签名:
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
如果我不将 key 导入 android keystore ,并尝试使用该 key 进行签名,则它可以工作。

如果我直接在 AndroidKeyStore 中生成 key ,它也会因相同的错误而失败。

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

最佳答案

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

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.

关于android - 无法使用导入到 AndroidKeyStore RSA 私钥进行签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59131150/

相关文章:

android - Kotlin:使用用 Java 编写的库时无法访问 lambda 函数内的代码

arrays - 具有泛型返回类型的 lambda 构造函数的 Kotlin NDArray

security - POSTing 时是否可以在 Web 应用程序中使用 RSA 加密而不是 SSL?

android - 导入预构建对象框数据库

android - 通过 Java 连接 GCM 时获取 JSON 异常

android - 在 kotlin 中找不到 getChildFragmentManager()

ios - 使用 iOS swift4 验证 JWT token 的签名

c# - 解码 OAEP 填充时出错

android - Android 中的位置更改

Android 屏幕以编程方式打开