简体   繁体   中英

Reading a certificate signing request with C#

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.

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.

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);

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 .

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.

To read Certificate Signing request, you can use method LoadSigningRequestPem availaible in class - "System.Security.Cryptography.X509Certificates.CertificateRequest".

using System.Security.Cryptography.X509Certificates;
string csr = @"-----BEGIN CERTIFICATE REQUEST-----
MIICvDCCAaQCAQAwdzELMAkGA1UEBhMCVVMxDTALBgNVBAgMBFV0YWgxDzANBgNV
BAcMBkxpbmRvbjEWMBQGA1UECgwNRGlnaUNlcnQgSW5jLjERMA8GA1UECwwIRGln
aUNlcnQxHTAbBgNVBAMMFGV4YW1wbGUuZGlnaWNlcnQuY29tMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8+To7d+2kPWeBv/orU3LVbJwDrSQbeKamCmo
wp5bqDxIwV20zqRb7APUOKYoVEFFOEQs6T6gImnIolhbiH6m4zgZ/CPvWBOkZc+c
1Po2EmvBz+AD5sBdT5kzGQA6NbWyZGldxRthNLOs1efOhdnWFuhI162qmcflgpiI
WDuwq4C9f+YkeJhNn9dF5+owm8cOQmDrV8NNdiTqin8q3qYAHHJRW28glJUCZkTZ
wIaSR6crBQ8TbYNE0dc+Caa3DOIkz1EOsHWzTx+n0zKfqcbgXi4DJx+C1bjptYPR
BPZL8DAeWuA8ebudVT44yEp82G96/Ggcf7F33xMxe0yc+Xa6owIDAQABoAAwDQYJ
KoZIhvcNAQEFBQADggEBAB0kcrFccSmFDmxox0Ne01UIqSsDqHgL+XmHTXJwre6D
hJSZwbvEtOK0G3+dr4Fs11WuUNt5qcLsx5a8uk4G6AKHMzuhLsJ7XZjgmQXGECpY
Q4mC3yT3ZoCGpIXbw+iP3lmEEXgaQL0Tx5LFl/okKbKYwIqNiyKWOMj7ZR/wxWg/
ZDGRs55xuoeLDJ/ZRFf9bI+IaCUd1YrfYcHIl3G87Av+r49YVwqRDT0VDV7uLgqn
29XI1PpVUNCPQGn9p/eX6Qo7vpDaPybRtA2R7XLKjQaF9oXWeCUqy1hvJac9QFO2
97Ob1alpHPoZ7mWiEuJwjBPii6a9M9G30nUo39lBi1w=
-----END CERTIFICATE REQUEST-----";
CertificateRequest certReq = CertificateRequest.LoadSigningRequestPem(csr,HashAlgorithmName.SHA256);
Console.WriteLine("Subject Name: {0}",certReq.SubjectName.Name);

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM