AsnContentException:提供的数据标记为“通用”类值“16”,但它应该是“通用”类值“2”

pan*_*nis 7 .net c# security rsa bouncycastle

我正在尝试使用 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 _);
Run Code Online (Sandbox Code Playgroud)

有人知道我为什么会收到这个吗?

Top*_*aco 6

正如 James K. Polk 总统在评论中所述,导出的公钥serializedPublicBytes是 X.509/SPKI 格式的 DER 编码密钥,可以使用 导入ImportSubjectPublicKeyInfo(),同时ImportRSAPublicKey()需要 PKCS#1 格式的 DER 编码公钥。

publicKeyInfo为了完整起见:通过在发布的代码中添加以下内容,可以轻松导出 PKCS#1 格式:

RsaPublicKeyStructure rsaPublicKey = RsaPublicKeyStructure.GetInstance(publicKeyInfo.ParsePublicKey());
byte[] pkcs1Der = rsaPublicKey.ToAsn1Object().GetDerEncoded();
Run Code Online (Sandbox Code Playgroud)

这样导入也可以通过ImportRSAPublicKey()传递来完成pkcs1Der,或者如果需要 PKCS#1 格式的公钥。