简体   繁体   English

从X509Certificate2删除私钥

[英]remove private key from X509Certificate2

I'm using the following method to export a certificate chain that contains two X509Certificate2 objects: a certificate and the Certificate Authority that issued it: 我正在使用以下方法导出包含两个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);                        
}

the problem, as the comment in the code already tells, is that nulling the private key throws an exception that tells me "access denied" 正如代码中的注释所表明的那样,问题在于私有密钥为空会引发异常,告诉我“访问被拒绝”

How do I properly remove the private key from a X509Certificate2 object (or, alternatively, how do I get it from the store WITHOUT the private key in the first place? 我如何从X509Certificate2对象中正确删除私钥(或者,如何从商店中获取私钥而不首先使用私钥?

Well, I found a workaround while waiting for answers, which is this: 好吧,我在等待答案时发现了一种解决方法,这是:

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

basically, this does an on-the-fly export of the CA certificate without the private key, and then immediately re-builds it back to a new X509Certificate2 object. 基本上,这会在没有私钥的情况下即时导出CA证书,然后立即将其重新构建回新的X509Certificate2对象。

Still leaving this question open for a bit, in case someone else points out a more "proper" solution. 万一其他人指出了一个更“合适”的解决方案,这个问题仍有待解决。 But this seems to work well. 但这似乎运作良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM