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

后端 未结 1 1826
我寻月下人不归
我寻月下人不归 2020-12-02 18:45

I\'ve been googling around for half a day looking for a way to read a .pfx file and import the certificates into the certstore.

So far, I am a

相关标签:
1条回答
  • 2020-12-02 18:59

    You should be able to get a collection object containing the certs in your .pfx file by using the X509Certificate2Collection class... here'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:

    http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx

    And the different members in the StoreName enumeration:

    http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.storename.aspx

    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.

    0 讨论(0)
提交回复
热议问题