Compartilhar via


Exemplo de código de geração de solicitação de assinatura de certificado (CSR)

O exemplo de código a seguir gera um CSR com a biblioteca BouncyCastle C#.

Nota: Este não é um exemplo completo e não armazena com segurança a chave privada. Isso é apenas para fins de ilustração.

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