Partager via


Exemple de code de génération de demande de signature de certificat (CSR)

L’exemple de code suivant génère une demande de signature de certificat avec la bibliothèque C# BouncyCastle .

Remarque : Il ne s’agit pas d’un exemple complet et ne stocke pas en toute sécurité la clé privée. Cela n’est qu’à des fins d’illustration.

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