如何在保留私钥的同时将 BouncyCastle X509Certificate 转换为 .NET Standard X509Certificate2?

How to convert BouncyCastle X509Certificate to .NET Standard X509Certificate2 while retaining the private key?

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

有一个类似问题的答案 ,但在生成 BouncyCastle 证书并将其转换为 .NET X509Certificate2 后,生成的对象具有其 HasPrivateKey 属性 设置为 "false".

上下文

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

我得到了为此使用 BouncyCastle 的建议 (),所以我首先从 Base64 字符串生成一个 BouncyCastle X509Certificate,然后尝试将其转换为 X509Certificate2同时保留私钥。

我发现的最佳方法是通过内存中的 PFX 流。假设您已经在 bcCert 中加载了您的 Bouncy Castle 证书。注意:如果您要在任何地方保存 .NET X509Certificate2,"alias" 就是稍后在 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());
}