Search code examples
c#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:

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?


Solution

  • 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.

    Still leaving this question open for a bit, in case someone else points out a more "proper" solution. But this seems to work well.