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