将私钥和证书导出到PFX - C#

时间:2015-05-05 12:42:09

标签: c# .net ssl bouncycastle x509certificate2

实际上我有privateKey字符串和带有rootCertificate和证书的X509Certificate2Collection。有什么办法可以一次性将所有这些导出到pfx文件吗?

我的代码:

var p7b = new WebClient().DownloadData(
          ConfigurationManager.AppSettings["certSrv"] + "/CertSrv/CertNew.p7b?ReqID=" +
          caResponse.CertRequest.GetRequestId() + "&Enc=bin");

var certCollection = new X509Certificate2Collection();
certCollection.Import(p7b);

var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream);
var pemWriter = new PemWriter(streamWriter);
pemWriter.WriteObject(caRequest.PrivateKey);
streamWriter.Flush();

var output = Encoding.ASCII.GetString(memoryStream.GetBuffer()).Trim();
var index_of_footer = output.IndexOf("-----END RSA PRIVATE KEY-----");
memoryStream.Close();
streamWriter.Close();

var key = output.Substring(0, index_of_footer + 29);
var pfx = certCollection.Export(X509ContentType.Pkcs12, password);

在我的代码中,我只导出我拥有的证书。

0 个答案:

没有答案