How can I save a CertificationRequest out to a .csr file?

0 votes
asked Feb 20 by Robert Montgomery (120 points)

I found this question and was able to successfully create a CertificationRequest:

But how do I save this out to a .csr file?
Unlike Certificate and PrivateKeyInfo, there is not a save method on the CertificationRequest.

1 Answer

0 votes
answered Feb 21 by Lukas Matyska (43,090 points)

You are right. The CertificationRequest class have no Save method. We will add it in future.

In the meantime, you can simply write it for yourself:

public static void Save(CertificationRequest request, string path)
    // encode request to base64
    byte[] encoded = request.Encode();
    string base64 = Convert.ToBase64String(encoded, Base64FormattingOptions.InsertLineBreaks);

    // write request to a file
    using (var writer = new StreamWriter(File.Create(path)))
        writer.WriteLine("-----BEGIN CERTIFICATE REQUEST-----");
        writer.Write("-----END CERTIFICATE REQUEST-----");

The whole process can look like this:

// generate new public/private key
var alg = new AsymmetricKeyAlgorithm();
alg.GenerateKey(AsymmetricKeyAlgorithmId.RSA, 2048);
var privateKey = alg.GetPrivateKey();
var publicKey = alg.GetPublicKey();

// create certification request
var request = new CertificationRequest(new DistinguishedName(", O=Example"), publicKey);
// fill required data (depends on issuing authority)
request.CertificateExtensions.Add(CertificateExtension.EnhancedKeyUsage(false, ExtendedUsageOids.ServerAuthentication));
// sign the request
request.Sign(privateKey, SignatureHashAlgorithm.SHA256);

// save request to a .csr file
Save(request, @"c:\data\example.csr");