通过RSA 2048私钥解密字符串时发生IllegalBlockSizeException

时间:2018-11-14 06:28:56

标签: android kotlin rsa

我试图通过RSA 2048私钥解密字符串,但是发生以下错误。

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811) 
     Caused by: javax.crypto.IllegalBlockSizeException: input must be under 256 bytes
        at com.android.org.conscrypt.OpenSSLCipherRSA.engineDoFinal(OpenSSLCipherRSA.java:245)
        at javax.crypto.Cipher.doFinal(Cipher.java:1340)

这是我的代码:

private fun rsaDecrypt(key: String, plain: String): String {
    var privateKey = ""
    if (key.contains("-----BEGIN RSA PRIVATE KEY-----") || key.contains("-----END RSA PRIVATE KEY-----")) {
        privateKey = key.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", "")
    }

    val base64Key = Base64.decode(privateKey.toByteArray(Charsets.UTF_8), Base64.DEFAULT)
    val spec = PKCS8EncodedKeySpec(base64Key)
    val keyFactory = KeyFactory.getInstance("RSA", "BC")
    val rsaPrivateKey = keyFactory.generatePrivate(spec)

    val cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")
    cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey)
    val decryptedBytes = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))

    return Base64.encodeToString(decryptedBytes, Base64.DEFAULT)
}

加密的字符串:

fhTGWW3Zn/nnhXoQO2Y3eKfYkBe/um7XUu2SlrnXMHT7tqT+KvcEUWXnJvLgN7/jpJp8ZOFvHiB6w8OFjPob7VSzQbyultpkFvBGZR7Z6j8m24IoqAPj2OhZDPQ4W8kza4eu/LP2560MfcbJqblOG0tcVF72fQ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fx/AEeJ3GhvkMfNBwZcaQtngK2UKu9rRsaF7bitL4intxU/EtmpDHU0CgYEAmDDs
jgbTkmgLsp7/vzot+lMTv6er4KB3AHTJWY9pDkNv5vvcyd/I04S/vFDar8FvlrXM
qlcAYptnpUBUPWJ43cnE8VBz2pwInNzty490YHH1mQ622801vAOiZ0t7dowypuip
qE3zYTRUc+qqZmeZYw8IWX/uqxizz67yHelrTZsCgYBZZ6ta+Ml+hlGMQgtI951Z
edDLG4HI+3Fd0aJZVn6o8m9nffkqflbxlpHukV8AG13YMmZhBwq1ZM16ezRIMzgk
oX4Tr0w126AwZfWEVkocMD3yX1R2oT2g2YIY8OChuYz/tgfwFtyRXp9HBphoRO94
bhJkF5i1ZQkoLStx2793wQKBgD4827BlSEZ6ODZu4WWhdEYHjW72McrltGTCXck7
ZZoIqA2M+EiyNJ2TjxmC8zum3myColUSyTyKEwO4X/rOd2Ez709EOGyxHLCRhMmX
O99pGyfhpZQTwqLF1bdqXe4n/VrWkPMcFaitzs+sqszAFzE0Z5S6Ra9ApeALykXD
PDd7AoGBAPQEoz1MYCT58LMwZwJJPeX6RbHp0j9rnzOoHcZof2XBCZ1JmTDtQ6F7
P1Exmmt/UH1km0Nq/caJx2M751bAPP+hM5t4ycZAzpQQsiZaXHDtq+OAIAPyC+vf
nnfSk8udDv445chqGZiMGIwg3XavoUJ5yzu8CTKd5dItxPwzG46Z
-----END RSA PRIVATE KEY-----

如何解密字符串?

1 个答案:

答案 0 :(得分:0)

问题很简单。您无法对plain参数进行base64解码。另外,Bouncycastle提供程序在其PKCS8EncodedKeySpec生成器中有些宽容。如果传递的数据不是PKCS8,则尝试将其解析为PKCS #1 RSA Private key,只有失败了,它才最终引发异常。您的私钥是根据PKCS#1而不是PKCS#8格式化的。