我正在尝试使用 BouncyCastle 创建 RSA 密钥对,然后尝试导入生成的公钥,但收到以下错误
AsnContentException: The provided data is tagged with 'Universal' class value '16', but it should have been 'Universal' class value '2'.
代码如下
RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
AsymmetricCipherKeyPair keys = rsaKeyPairGenerator.GenerateKeyPair();
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
RSA publicRsaKey = RSA.Create();
publicRsaKey.ImportRSAPublicKey(serializedPublicBytes, out _);
有人知道我为什么会收到这个吗?
正如 James K. Polk 总统的评论中已经描述的那样,导出的公钥serializedPublicBytes
是 X.509/SPKI 格式的 DER 编码密钥,可以使用以下命令导入ImportSubjectPublicKeyInfo()
, while ImportRSAPublicKey()
需要 PKCS#1 格式的 DER 编码公钥。
为了完整起见:PKCS#1 格式可以轻松地从publicKeyInfo
在发布的代码中添加以下内容:
RsaPublicKeyStructure rsaPublicKey = RsaPublicKeyStructure.GetInstance(publicKeyInfo.ParsePublicKey());
byte[] pkcs1Der = rsaPublicKey.ToAsn1Object().GetDerEncoded();
这样导入也可以通过ImportRSAPublicKey()
通过pkcs1Der
,或者如果需要 PKCS#1 格式的公钥。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)