Certificate Signing Request (CSR) Generation Code Sample

The following code sample generates a CSR with the BouncyCastle C# library.

Note: This is not a complete sample and does not securely store the private key. This is only for illustration purposes.

var keyPair = GenerateKeyPair();
var keyPem = new StringBuilder();
var keyPemWriter = new PemWriter(new StringWriter(keyPem));
keyPemWriter.WriteObject(keyPair.Public);
keyPemWriter.Writer.Flush();

var transportKey = RemovePemHeaderFooter(keyPem.ToString());
var csrData = GenerateCertRequest(keyPair);

public static AsymmetricCipherKeyPair GenerateKeyPair()
{
    // Generate private/public key pair
    RsaKeyPairGenerator generator = new RsaKeyPairGenerator();
    KeyGenerationParameters keyParams = new KeyGenerationParameters(new SecureRandom(), 2048);
    generator.Init(keyParams);
    return generator.GenerateKeyPair();
}

private static string RemovePemHeaderFooter(string input)
{
    var headerFooterList = new List\<string\>()
    {
        "-----BEGIN CERTIFICATE REQUEST-----",
        "-----END CERTIFICATE REQUEST-----",
        "-----BEGIN PUBLIC KEY-----",
        "-----END PUBLIC KEY-----",
        "-----BEGIN RSA PRIVATE KEY-----",
        "-----END RSA PRIVATE KEY-----"
    };

    string trimmed = input;
    foreach (var hf in headerFooterList)
    {
        trimmed = trimmed.Replace(hf, string.Empty);
    }

    return trimmed.Replace("\r\n", string.Empty);
}

private static string GenerateCertRequest(AsymmetricCipherKeyPair keyPair)
{
    var values = new Dictionary<DerObjectIdentifier, string> {
    {X509Name.CN, "Microsoft"}, //domain name inside the quotes
    {X509Name.O, "Microsoft Corp"}, //Organisation\'s Legal name inside the quotes
    {X509Name.L, "Redmond"},
    {X509Name.ST, "Washington"},
    {X509Name.C, "US"},
    };

    var subject = new X509Name(values.Keys.Reverse().ToList(), values);
    var csr = new Pkcs10CertificationRequest(
    new Asn1SignatureFactory("SHA256withRSA", keyPair.Private),
    subject,
    keyPair.Public,
    null,
    keyPair.Private);

    //Convert BouncyCastle csr to PEM format
    var csrPem = new StringBuilder();
    var csrPemWriter = new PemWriter(new StringWriter(csrPem));
    csrPemWriter.WriteObject(csr);
    csrPemWriter.Writer.Flush();
    return RemovePemHeaderFooter(csrPem.ToString());
}