从 RSACryptoServiceProvider 解码密钥

Decoding the keys from RSACryptoServiceProvider

我正在尝试使用 .ExportRSAPrivateKey()RSACryptoServiceProvider 对象中提取私钥。根据 MSDN, it exports a "byte array containing the PKCS#1 RSAPrivateKey representation of this key", which representation is defined in Appendix A of RFC8017。因此,基于此,我假设它应该是 ASN1 编码的,并尝试使用 AsnReader class:

using (var rsa = new RSACryptoServiceProvider(1024))
{
    var priv = rsa.ExportRSAPrivateKey();
    var asnr = new AsnReader(priv, AsnEncodingRules.DER);
    var N = asnr.ReadInteger();
}

但是,此代码在 .ReadInteger() 上失败,例外情况是:"The provided data is tagged with 'Universal' class value '16', but it should have been 'Universal' class value '2'."

我做错了什么?

这是因为 RSAPublicKey 是一个 SEQUENCE ...

所以你必须读取一个序列,然后,整数...

我猜你使用的是 Microsoft AsnReader class

因此,代码可能类似于:

var publicKey = asnr.ReadSequence()
var N = publickKey.ReadInteger()