Reading a certificate signing request with C#

Jorge picture Jorge · May 14, 2010 · Viewed 14.2k times · Source

I want to read the contents of a CSR in C#. However, I haven't found any way to do it in C#. What I've found was the namespace System.Security.Cryptography.X509Certificates, but it only handles existing certificates, not certificate requests.

Can anyone give me an hint about it? Thanks in advance.

Answer

blowdart picture blowdart · Mar 22, 2011

There is a way, the CertEnroll library which comes with Windows (although I can't say how far back it's been there) allows you to load certificate requests and have them parsed.

First you need to import a reference to the CERTENROLLLib COM library into your project. This will create a CERTENROLLLib name space you can then use.

Then you do something like this;

string csr = "-----BEGIN CERTIFICATE REQUEST-----\r\n" +
             "MIIBnTCCAQYCAQAwXTELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIw\r\n" +
             "EAYDVQQDEwlsb2NhbGhvc3QxJzAlBgkqhkiG9w0BCQEWGGFkbWluQHNlcnZlci5l\r\n" +
             "eGFtcGxlLmRvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAr1nYY1Qrll1r\r\n" +
             "uB/FqlCRrr5nvupdIN+3wF7q915tvEQoc74bnu6b8IbbGRMhzdzmvQ4SzFfVEAuM\r\n" +
             "MuTHeybPq5th7YDrTNizKKxOBnqE2KYuX9X22A1Kh49soJJFg6kPb9MUgiZBiMlv\r\n" +
             "tb7K3CHfgw5WagWnLl8Lb+ccvKZZl+8CAwEAAaAAMA0GCSqGSIb3DQEBBAUAA4GB\r\n" +
             "AHpoRp5YS55CZpy+wdigQEwjL/wSluvo+WjtpvP0YoBMJu4VMKeZi405R7o8oEwi\r\n" +
             "PdlrrliKNknFmHKIaCKTLRcU59ScA6ADEIWUzqmUzP5Cs6jrSRo3NKfg1bd09D1K\r\n" +
             "9rsQkRc9Urv9mRBIsredGnYECNeRaK5R1yzpOowninXC\r" + 
             "-----END CERTIFICATE REQUEST-----";

CX509CertificateRequestPkcs10 request = new CX509CertificateRequestPkcs10();
request.InitializeDecode(csr, EncodingType.XCN_CRYPT_STRING_BASE64_ANY);
request.CheckSignature();

Console.WriteLine(((CX500DistinguishedName)request.Subject).Name);
Console.WriteLine(request.PublicKey.Length);
Console.WriteLine(request.HashAlgorithm.FriendlyName);

You can see the only fun part is getting the subject name out, as you need to cast it to a CX500DistinguishedName instance first.