【问题标题】:How to convert BouncyCastle X509Certificate to .NET Standard X509Certificate2 while retaining the private key?如何在保留私钥的同时将 BouncyCastle X509Certificate 转换为 .NET Standard X509Certificate2?
【发布时间】:2017-06-16 12:38:40
【问题描述】:

我需要将生成的 BouncyCastle X509Certificate 转换为 X509Certificate2,并将私钥加载到生成的 .NET Standard X509Certificate2 对象中。那可能吗?

有一个类似问题的答案 https://stackoverflow.com/a/8150799/5048935 ,但是在生成 BouncyCastle 证书并将其转换为 .NET X509Certificate2 后,结果对象的 HasPrivateKey 属性设置为“false”。

上下文

我需要将证书和私钥(没有页眉和页脚的单独 Base64 字符串)加载到 X509Certificate2 对象,以将其从 .NET Standard 1.6 库传递到应用程序。问题是,.NET Standard 中的 X509Certificate2 类中没有 PrivateKey 属性!因此,我在X509Certificate2 对象中实际加载私钥的唯一方法是将其与 .pfx 文件中的证书本身结合起来,然后像在构造函数中那样加载它。

我有使用 BouncyCastle 的建议 (https://stackoverflow.com/a/44465965/5048935),所以我首先从 Base64 字符串生成 BouncyCastle X509Certificate,然后尝试在保留私钥的同时将其转换为 X509Certificate2

【问题讨论】:

  • 您能否发布一些代码,以便我们查看您目前的成果?

标签: c# ssl-certificate x509certificate bouncycastle .net-standard


【解决方案1】:

我发现最好的方法是通过内存中的 PFX 流。假设您已经在bcCert 中加载了 Bouncy Castle 证书。注意:如果您要将 .NET X509Certificate2 保存在任何地方,“别名”是稍后将在 UI 中调用的名称,否则它是无关紧要的(除非两个调用必须相同)。

using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using System.IO;
using System.Security.Cryptography.X509Certificates

var pkcs12Store = new Pkcs12Store();
var certEntry = new X509CertificateEntry(bcCert);
pkcs12Store.SetCertificateEntry(alias, certEntry);
pkcs12Store.SetKeyEntry(alias, new AsymmetricKeyEntry(certKey.Private), new[] { certEntry });    
X509Certificate2 keyedCert;
using (MemoryStream pfxStream = new MemoryStream())
{
    pkcs12Store.Save(pfxStream, null, new SecureRandom());
    pfxStream.Seek(0, SeekOrigin.Begin);
    keyedCert = new X509Certificate2(pfxStream.ToArray());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 2018-04-20
    • 2016-02-17
    • 2019-05-05
    • 2013-07-17
    • 2010-09-17
    • 2013-08-30
    • 2017-09-07
    相关资源
    最近更新 更多