Search code examples
c#x509x509certificate2

How to extract the AuthorityKeyIdentifier from a X509Certificate2 in .NET


I am looking for a way to extract the AuthorityKeyIdentifier extension from an X509Certificate2 instance. I did not see any built-in support for this but since windows can properly construct a certificate chain I know the functionality has to exist at some level. If the answer is to roll a DER parser, is there a good implementation that can be referenced?


Solution

  • Iterate through the extensions in the X509Certificate2.Extensions property and look for an extension with the OID 2.5.29.35 (as per http://www.alvestrand.no/objectid/2.5.29.35.html). That is the AuthorityKeyIdentifier extension.

    [Edit: Added the following.]

    Each member of the Extensions property is an ASN encoded. So you can do the following to get it in a human readable or machine parsable format:

    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    
    ...
    
    X509Extension extension; // The OID 2.5.29.35 extension
    AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
    Console.WriteLine(asndata.Format(true));
    

    For one of the Microsoft intermediate CA certificates, it the Format() method returns the following:

    [1]Authority Info Access
         Access Method=Certification Authority Issuer (1.3.6.1.5.5.7.48.2)
         Alternative Name:
              URL=http://www.microsoft.com/pki/certs/MicrosoftRootCert.crt
    

    It is certainly not easy to parse but you can look for a line starting with the regular expression \[\d+\]Authority Info Access then find a line beneath it with the regular expression URL=(.+) (the eight spaces are unclear in the formatting) and use the URL in the parenthesized group.