首页 > 解决方案 > 将 PrivateKey 编码为 PKCS#1 格式,然后恢复为 PrivateKey

问题描述

我有一个 2048 位 RSA PublicKey,我希望将其转换为 PKCS#1 格式的 ByteArray,然后从该 ByteArray 中恢复 PublicKey 对象。我正在使用 JVM 上的 Kotlin 使用 BouncyCastle 转换为 PKCS#1,代码如下:

fun privKeyToPkcs1Bytes(privKey: PrivateKey): ByteArray {
    val privKeyInfo = PrivateKeyInfo.getInstance(privKey.encoded)
    val privKeyAsn1Encodable: ASN1Encodable = privKeyInfo.parsePrivateKey()
    val privKeyAsn1Primitive: ASN1Primitive = privKeyAsn1Encodable.toASN1Primitive()
    val privKeyPkcs1Bytes: ByteArray = privKeyAsn1Primitive.getEncoded()
    return privKeyPkcs1Bytes
}

然后我尝试使用以下代码将返回的 ByteArray 恢复为 PrivateKey 对象:

fun privKeyFromPkcs1Bytes(privKeyPkcs1Bytes: ByteArray): PrivateKey {
    val rsaPrivKey: RSAPrivateKey = RSAPrivateKey.getInstance(ASN1Sequence.fromByteArray(privKeyPkcs1Bytes))
    val privKeySpec: RSAPrivateKeySpec = RSAPrivateKeySpec(rsaPrivKey.modulus, rsaPrivKey.privateExponent)
    val privKey: PrivateKey = KeyFactory.getInstance("RSA").generatePrivate(privKeySpec)
    return privKey
}

代码运行没有错误,但原始 PrivateKey 和恢复的 PrivateKey 的 PKCS#8 表示不匹配。我已彻底寻找解决此问题的方法,但没有找到有效的解决方案。我在这里做错了什么?

标签: javakotlinencryptioncryptographybouncycastle

解决方案


推荐阅读