0 votes
by (120 points)

I found this question and was able to successfully create a CertificationRequest:
http://forum.rebex.net/6566/how-can-i-create-a-self-signed-server-certificate

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
by (72.7k 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.WriteLine(base64);
        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("CN=example.org, O=Example"), publicKey);
// fill required data (depends on issuing authority)
request.CertificateExtensions.Add(CertificateExtension.KeyUsage(KeyUses.DigitalSignature));
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");
...