0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

cscの作法 その218

Posted at

概要

cscの作法、調べてみた。
BouncyCastle.dll使ってみた。
秘密鍵と証明書から、キーストア(p12)を作ってみた。

サンプルコード

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Operators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

namespace ConsoleExample
{
	class Program {
		static void Main(string[] args) {
			AsymmetricCipherKeyPair privateKey;
			Org.BouncyCastle.X509.X509Certificate readedCert;
			using (var reader = new StreamReader(@"privatekey.pem", Encoding.ASCII))
			{
				var pemReader = new PemReader(reader);
				privateKey = (AsymmetricCipherKeyPair) pemReader.ReadObject();
			}
			using (var reader = new StreamReader(@"certificate.crt", Encoding.ASCII))
			{
				var pemReader = new PemReader(reader);
				readedCert = (Org.BouncyCastle.X509.X509Certificate) pemReader.ReadObject();
			}
			var randGen = new CryptoApiRandomGenerator();
			var rand = new SecureRandom(randGen);
			var certEntry = new X509CertificateEntry(readedCert);
			var keyEntry = new AsymmetricKeyEntry(privateKey.Private);
			var p12 = new Pkcs12Store();
			p12.SetCertificateEntry("test16", certEntry);
			p12.SetKeyEntry("key", keyEntry, new X509CertificateEntry[] {
				certEntry
			});
			using (var stream = new FileStream(@"test16.p12", FileMode.Create))
			{
				p12.Save(stream, "password".ToCharArray(), rand);
				stream.Flush();
			}
			Console.WriteLine("OK");
		}
	}
}



以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?