更新时间:2023-02-11 18:49:41
我发现的***方法是通过内存中的PFX流。假设您已经在 bcCert
中加载了Bouncy Castle证书。注意:如果要在任何地方保存.NET X509Certificate2
,则稍后将在用户界面中调用别名,否则就无关紧要了(除了
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());
}