Decoding the keys from RSACryptoServiceProvider

Viewed 865

I am trying to extract the private keys from an RSACryptoServiceProvider object using .ExportRSAPrivateKey(). As per MSDN, it exports a "byte array containing the PKCS#1 RSAPrivateKey representation of this key", which representation is defined in Appendix A of RFC8017. So based on that, I assume that it should be ASN1-encoded and try to use an AsnReader class:

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

However, this code fails on .ReadInteger() with exception: "The provided data is tagged with 'Universal' class value '16', but it should have been 'Universal' class value '2'."

What am I doing wrong?

1 Answers

It's because RSAPublicKey is a SEQUENCE ...

So you have to read a sequence and then, the integer ...

I guess you are using Microsoft AsnReader class

So, the code could be something like:

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