简体   繁体   中英

How to create a X509 certificate from Bouncy Castle for use with AuthenticateAsServer?

I've used Bouncy Castle to create an X509 certificate, but I can't use that together with SslStream.AuthenticateAsServer or SslStream.AuthenticateAsClient since they (of course) use the .Net version. Although there is a converter , DotNetUtilities.ToX509Certificate() , in Bouncy Castle which takes aa BC X509 and returns a .Net X509. The problem seems to be that AuthenticateAsServer/AuthenticateAsClient needs a certificate with the private key included. At least when I try to just convert and then use the new certificate I get a CryptographicException: "Key does not exist" when trying to connect using SslStream.

So I thought that I need to create an X509Certificate2 from Bouncy Castle, since that can contain the private key as well. But the solution I found seems a bit...odd, and I was wondering if anyone else now a better way to use a BC X509Certificate with SslStream.

This is how I create a X509Certificate2 from a BC Certificate:

private static X509Certificate CreateDotNetCertificate(Org.BouncyCastle.X509.X509Certificate certificate, AsymmetricCipherKeyPair keyPair)
{
   var store = new Pkcs12Store();
   string friendlyName = certificate.SubjectDN.ToString();
   var certificateEntry = new X509CertificateEntry(certificate);
   store.SetCertificateEntry(friendlyName, certificateEntry);
   store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyPair.Private), new[] { certificateEntry });

   var stream = new MemoryStream();
   var password = "a password";
   store.Save(stream, password.ToCharArray(), new SecureRandom(randomGenerator));

   return new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
}

It seems a bit weird that I need to take a "detour" through a Pkcs12Store to be able to create my X509Certificate2.

The solution is taken from this blog: http://blog.differentpla.net/post/20

Windows works with certificates stored in Windows Certificate Storage . I don't know if BouncyCastle provides direct access to Windows CertStorage but if it doesn't, than the only option is to import the certificate to CertStorage from file (or from other source), then use it. PKCS#12 is the right format to transfer the certificate with its private key together, so it's quite natural to use it as an intermediate medium.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM