更新时间:2023-02-11 19:16:33
我发现的***方法是通过内存中的 PFX 流.假设您已经在 bcCert
中加载了 Bouncy Castle 证书.注意:如果您要将 .NET X509Certificate2
保存在任何地方,则别名"是稍后将在 UI 中调用的内容,否则无关紧要(除了需要相同外)两个电话).
The best way I've found is to go through an in-memory PFX stream. Assuming you've already loaded your Bouncy Castle cert in bcCert
. Note: If you are going to be saving the .NET X509Certificate2
anywhere, the "alias" is what it's going to be called in the UI later, otherwise it's irrelevant (other than it needs to be the same for both calls).
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());
}