从 X509Certificate2 中删除私钥

remove private key from X509Certificate2

我正在使用以下方法导出包含两个 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);                        
}

正如代码中的注释已经说明的那样,问题是使私钥为空会引发异常,该异常告诉我 "access denied"

如何正确地从 X509Certificate2 对象中删除私钥(或者,我如何在没有私钥的情况下从商店中获取它?

好吧,我在等待答案时找到了一个解决方法,就是这个:

ca = new X509Certificate2(ca.Export(X509ContentType.Cert));

基本上,这会在没有私钥的情况下即时导出 CA 证书,然后立即将其重建回新的 X509Certificate2 对象。

这个问题仍然悬而未决,以防其他人指出更 "proper" 的解决方案。但这似乎很有效。