Chloé Chloé - 1 year ago 236
C# Question

How to retrieve certificates from a pfx file with c#?

I've been googling around for half a day looking for a way to read a

file and import the certificates into the certstore.

So far, I am able to read the
file with
and able to import one certificate within the
file. So far so good, but there are three certificates in the
file and when loading the
, I am not able to see the other two certificates.

The certificate was exported with

*Personal Information Exchange - PKCS #12 (.PFX)

  • Include all certificates in the certification path if possible

  • Enable strong protection (requires IE 5.0, NT 4.0 SP4 or above)

Those are the options selected when exporting the certificate(s). I know there are three certificates because I manually go into the certstore (MMC) and import it into a personal folder myself.

Answer Source

You should be able to get a collection object containing the certs in your .pfx file by using the X509Certificate2Collection's some C# example code:

string certPath = <YOUR PFX FILE PATH>;
string certPass = <YOUR PASSWORD>;

// Create a collection object and populate it using the PFX file
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet);

Then you can iterate over the collection:

foreach (X509Certificate2 cert in collection)
    Console.WriteLine("Subject is: '{0}'", cert.Subject);
    Console.WriteLine("Issuer is:  '{0}'", cert.Issuer);

    // Import the certificates into X509Store objects

Depending on the type of certificate (client cert, intermediate CA cert, root CA) you'll need to open the proper cert store (as an X509Store object) to import it.

Check out the X509Store docs:

And the different members in the StoreName enumeration:

From what I understand, you want to use "StoreName.My" for client certificates that contain a private key, "StoreName.CertificateAuthority" for intermediate CA certs, and "StoreName.Root" for root CA certs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download