我需要将生成的 BouncyCastle
X509Certificate
转换为 X509Certificate2
,并将私钥加载到生成的 .NET Standard X509Certificate2
对象中。那可能吗?
类似问题有一个答案https://stackoverflow.com/a/8150799/5048935,但是在生成 BouncyCastle 证书并将其转换为 .NET
X509Certificate2
之后,生成的对象具有其 HasPrivateKey
属性集到“假”。
我需要将证书和私钥(没有页眉和页脚的独立 Base64 字符串)加载到
X509Certificate2
对象,以将其从 .NET Standard 1.6 库传递到应用程序。问题是,.NET Standard 中的 PrivateKey
类中没有 X509Certificate2
属性!因此,我在 X509Certificate2
对象中实际加载私钥的唯一方法是将其与 .pfx 文件中的证书本身结合起来,然后像在构造函数中一样加载它。
我收到了使用 BouncyCastle 的建议(https://stackoverflow.com/a/44465965/5048935),所以我首先从 Base64 字符串生成一个 BouncyCastle
X509Certificate
,然后尝试将其转换为 X509Certificate2
同时保留私钥。
我发现的最好方法是浏览内存中的 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());
}
Ashu,我无法直接回复您的评论,但对于较新版本的充气城堡,您可以将 Kevin 的答案更改为:
var pkcs12StoreBuilder = new Pkcs12StoreBuilder();
var pkcs12Store = pkcs12StoreBuilder.Build();