Reading a certificate signing request with C#

2020-06-16 03:09发布

问题:

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.

回答1:

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.



回答2:

It seems to me the best way for you is usage unmanaged CryptoAPI or P/Invoke. CryptoAPI has CERT_REQUEST_INFO data struct and CryptSignAndEncodeCertificate function which can be used with X509_CERT_REQUEST_TO_BE_SIGNED parameter. Of cause theoretically it's possible to encode request manually with respect of AsnEncodedData, because CSR is not complex (see http://en.wikipedia.org/wiki/Certificate_signing_request and http://www.rfc-editor.org/rfc/rfc2311.txt), but I don't think that it has a sense if an implementation already exist in CryptoAPI.

A good examples to create CSR with respect of CryptoAPI you will find in http://msdn.microsoft.com/en-us/library/aa382364(VS.85).aspx and http://msdn.microsoft.com/en-us/library/ms867026.aspx.



回答3:

This is how you do it with OpenSSL.NET library:

// Load the CSR file
var csr = new X509Request(BIO.File("C:/temp/test.csr", "r"));
OR
var csr = new X509Request(@"-----BEGIN CERTIFICATE REQUEST-----...");

// Read CSR file properties
Console.WriteLine(csr.PublicKey.GetRSA().PublicKeyAsPEM);
Console.WriteLine(csr.Subject.SerialNumber);
Console.WriteLine(csr.Subject.Organization);
.
.
.

X509Request type has properties to get everything out of your CSR file text.



回答4:

Look at BouncyCastle's C# implementation. Used it for PGP stuff in the past, worked great. Something like this should get you started (not tested):

var textReader = File.OpenText(...);
var reader = new Org.BouncyCastle.OpenSsl.PEMReader(textReader);
var req = reader.ReadObject() as Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest;
var info = req.GetCertificationRequestInfo();
Console.WriteLine(info.Subject);


回答5:

I had the same issue. I didn;t find a solution so "invented" ;) on a work around. CertUtil.exe is microsoft's command line utility to create, read,submit, accept and install certs. I used System.Diagnostics.Process to create external process and passed the CSR request file as argument to read the file into a stream. Heres the code for it.

using (System.Diagnostics.Process extProc = new System.Diagnostics.Process())
{
      extProc.StartInfo.CreateNoWindow = true;
      extProc.StartInfo.UseShellExecute = false;
      extProc.StartInfo.RedirectStandardOutput = true;

      extProc.StartInfo.FileName = @"C:\certtest\Util_xpVersion\certutil.exe";
      extProc.StartInfo.Arguments = "-dump \"C:\\certtest\\Util_xpVersion\\ToolCSR.crq\"";

      extProc.Start();
      extProc.WaitForExit();
      string sTemp = extProc.StandardOutput.ReadToEnd();
      extProc.Close();
}