証明書署名の要求 (CSR) 生成コード サンプル
次のコード サンプルでは、BouncyCastle C# ライブラリを使用してCSR を生成します。
注: これは完全なサンプルではなく、秘密キーは安全に格納されません。 これは例示のみを目的としています。
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());
}