我正在使用以下方法导出包含两个X509Certificate2
对象的证书链:证书和颁发证书的证书颁发机构:
public void ExportCertificateChain(X509Certificate2 cert, X509Certificate2 ca, string outPath, string password)
{
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Add(cert); //certificate with private key
//remove private key from CA, because don't want it to be usable for signing, we just want to install it to validate the first certificate
ca.PrivateKey = null; //This throws an "Access Denied" exception!!!
collection.Add(ca);
var raw = collection.Export(X509ContentType.Pfx, password);
File.WriteAllBytes(outPath, raw);
}
问题,正如代码中的注释已经说明的那样,将私钥置零会抛出一个异常,告诉我“访问被拒绝”
如何从X509Certificate2
对象中正确删除私钥(或者,如何在没有私钥的情况下从商店获取私钥?
答案 0 :(得分:5)
好吧,我在等待答案时找到了解决方法,这就是:
ca = new X509Certificate2(ca.Export(X509ContentType.Cert));
基本上,这会在没有私钥的情况下实时导出CA证书,然后立即将其重新构建回新的X509Certificate2
对象。
仍然暂时搁置这个问题,以防其他人指出更多"正确的"解。但这似乎运作良好。