C# read der encoded private key

hs2d picture hs2d · Apr 7, 2011 · Viewed 7k times · Source

How can I get the fields from ASN1 DER format private key? Is there a library to decode and get the fields separately?

I need to extract the modulus, exponent and all the other fields.

Or maybe is there a way to convert it to .net xml format?

Answer

GalacticJello picture GalacticJello · Feb 29, 2012

If all you want is to reduce the code needed to parse ASN.1, you could have a peek at the LCLib portion of the ASN.1 Editor project.

It is a simple ASN.1 processor library.

Using the sample DER encoded test string of "[email protected]" :

16 0d 74 65 73 74 31 40 72 73 61 2e 63 6f 6d

    using (var stm = new MemoryStream(new byte[] { 0x16, 0x0d, 0x74, 0x65, 0x73, 0x74, 0x31, 0x40, 0x72, 0x73, 0x61, 0x2e, 0x63, 0x6f, 0x6d }))
    {
        Asn1Parser parser = new Asn1Parser();
        parser.LoadData(stm);
        var decoded = parser.ToString();
    }

Gives the formatted output:

Offset| Len |LenByte| ======+======+=======+====

 0|    13|      1| IA5 STRING : '[email protected]'

You can walk the tree, and process the nodes as you wish.