views:

2752

answers:

3

Hi everyone,

I thought this would be straightforward but apparently it isn't. I have a certificate installed that has a private key, exportable, and I want to programmatically export it with the public key ONLY. In other words, I want a result equivalent to selecting "Do not export the private key" when exporting through certmgr and exporting to .CER.

It seems that all of the X509Certificate2.Export methods will export the private key if it exists, as PKCS #12, which is the opposite of what I want.

Is there any way using C# to accomplish this, or do I need to start digging into CAPICOM?

Thanks,

Aaron

+1  A: 

There is an OpenSSL .NET wrapper you may find useful.

Nathan
+1  A: 

For anyone else who might have stumbled on this, I figured it out. If you specify X509ContentType.Cert as the first (and only) parameter to X509Certificate.Export, it only exports the public key. On the other hand, specifying X509ContentType.Pfx includes the private key if one exists.

I could have sworn that I was seeing different behaviour last week, but I must have already had the private key installed when I was testing. When I deleted that certificate today and started again from scratch, I saw that there was no private key in the exported cert.

Aaronaught
A: 

I am using this simple code to test the above:

    X509Certificate2 cert = new X509Certificate2("C://test.pem");
    byte[] bytes = cert.Export(X509ContentType.Pfx, "abcd");
    File.WriteAllBytes("C://test.p12", bytes);

In all the cases I am unable to see private key in test.p12, I tried with X509ContentType.Pfx and X509ContentType.Pkcs12 I verified this using openssl utility by running the command

enter code hereopenssl pkcs12 -info -nodes -in test.p12

How are you getting both the keys exported. I want to get both the keys exported to my Pkcs12 file.

Devil Jin
I believe that PEM only holds the public key, it's similar to the Windows CER or PKCS #7 (.p7b). Most likely your private key isn't getting exported because it was never there in the first place.If you're sure that the PEM has a private key then maybe the DPAPI doesn't know how to read it. Try importing into certmgr and see if it gives you the exportable option.
Aaronaught