【问题标题】:How to create a X509 certificate from Bouncy Castle for use with AuthenticateAsServer?如何从 Bouncy Castle 创建 X509 证书以与 AuthenticateAsServer 一起使用?
【发布时间】:2014-05-28 05:28:54
【问题描述】:

我使用 Bouncy Castle 创建了 X509 证书,但我不能将它与 SslStream.AuthenticateAsServerSslStream.AuthenticateAsClient 一起使用,因为它们(当然)使用 .Net 版本。 尽管在 Bouncy Castle 中有一个转换器DotNetUtilities.ToX509Certificate(),它接受一个 BC X509 并返回一个 .Net X509。 问题似乎是 AuthenticateAsServer/AuthenticateAsClient 需要一个包含私钥的证书。至少当我尝试转换然后使用新证书时,我在尝试使用 SslStream 进行连接时得到CryptographicException: "Key does not exist"

所以我认为我需要从 Bouncy Castle 创建一个 X509Certificate2,因为它也可以包含私钥。但是我找到的解决方案似乎有点……奇怪,我想知道现在是否还有其他人可以更好地使用 BC X509Certificate 和 SslStream。

这就是我从 BC 证书创建 X509Certificate2 的方式:

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

我需要通过 Pkcs12Store “绕道”才能创建我的 X509Certificate2,这似乎有点奇怪。

解决方案摘自此博客:http://blog.differentpla.net/post/20

【问题讨论】:

  • 您的链接已损坏。你能添加正确的答案吗?
  • 很难相信使用 API “这么难”,但我赞成这篇文章,因为它是互联网上唯一一个我找到的答案肯定很丑但有效的地方!

标签: c# ssl x509certificate bouncycastle x509certificate2


【解决方案1】:

Windows 使用存储在 Windows 证书存储中的证书。我不知道 BouncyCastle 是否提供对 Windows CertStorage 的直接访问,但如果没有,则唯一的选择是将证书从文件(或其他来源)导入 CertStorage,然后使用它。 PKCS#12 是将证书与其私钥一起传输的正确格式,因此将其用作中间媒介是很自然的。

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2015-07-03
    • 2011-02-11
    • 1970-01-01
    • 2012-12-22
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多