java - 将 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 表示不匹配。我已彻底寻找解决此问题的方法,但没有找到有效的解决方案。我在这里做错了什么?
解决方案
推荐阅读
- javascript - OIDC 客户端 + 身份服务器 4,设置 max_age 静默令牌更新不起作用
- javascript - 如何将 NodeJS 中的 SSE 与第三方 API 调用集成
- java - 获取智能合约事件(web3j)
- javascript - 使用 JS 在购物车中渲染
- image-processing - 如何生成图像的像素数据
- git - Git describe 命令在没有任何更改后返回不同的值
- r - 和弦图:隐藏指向同一扇区的箭头
- c# - 异常中的错误代码
- java - 为什么@ComponentScan 对于不同的配置文件表现不同?
- flutter - 如何更改背景颜色并将自定义字体添加到我的介绍场景中?