【发布时间】:2014-05-28 05:28:54
【问题描述】:
我使用 Bouncy Castle 创建了 X509 证书,但我不能将它与 SslStream.AuthenticateAsServer 或 SslStream.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