How to programmatically import a pfx with a chain of certificates into the certificate store?

丶灬走出姿态 提交于 2019-11-27 19:46:42
Bill Agee

You should be able to iterate over the certs in your PFX (and import each into the cert store of your choice) by opening the PFX file as an X509Certificate2Collection object.

Here are the docs on X509Certificate2Collection:

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

MSDN provides some sample code in that docs page on how to inspect each cert in the collection.

Once you know the CNs/Issuers/other info about each cert it should be clear which certificate store each one needs to be added to. For that you can use the X509Store class and the StoreName enumeration to specify which store you want to open/add to:

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

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

Also see my answer to a similar SO question:

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

As mentioned in one of the latest comments on that answer, when you try to import a cert to the current user's Root store ("StoreName.Root" and "StoreLocation.CurrentUser" as the name/location) you will get a popup dialog asking you to confirm.

To solve that I just added a little MS UI Automation code to my cert import method, to click OK on the prompt.

Or, as the commenter "CodeWarrior" says in the other SO answer's comment, to avoid the popup dialog you can try putting the root cert into the LocalMachine store instead of CurrentUser.

Sample 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);

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

    // Import the certificate into an X509Store object
}

For future reference, I discovered another way of doing this, using the X509Chain object:

var cert = new X509Certificate2(pathToCert, password);

X509Chain chain = new X509Chain();
chain.Build(cert);
for (int i = 0; i < chain.ChainElements.Count; i++)
{
   //add to the appropriate store
}

For anyone who wants "to the appropriate store" code generic solution

This is what I've created using VB so shouldn't be to hard to port to C#. I used the above posts to get me started and I'm a total NooB at this.

    Dim certPath = "C:\Users\08353153\Documents\Visual Studio 2015\Projects\WindowsApplication2\WindowsApplication2\bin\Debug\8870-thebigchess.pfx"
    Dim certPass = "eduSTAR.NET"
    Dim Collection As New X509Certificate2Collection
    Collection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet)

    Dim certOne As X509Certificate2 = Collection(0)
    Dim certTwo As X509Certificate2 = Collection(2)
    Dim certThree As X509Certificate2 = Collection(1)

    Dim personal As New X509Store(StoreName.My, StoreLocation.LocalMachine)
    personal.Open(OpenFlags.ReadWrite)
    personal.Add(certOne)
    personal.Close()

    Dim trust As New X509Store(StoreName.Root, StoreLocation.LocalMachine)
    trust.Open(OpenFlags.ReadWrite)
    trust.Add(certTwo)
    trust.Close()

    Dim intermed As New X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine)
    intermed.Open(OpenFlags.ReadWrite)
    intermed.Add(certThree)
    intermed.Close()

An X.509 certificate contains only a chain that links it to the root certificate (including the intermediate authorities), but these certificates are not contained in the certificate. This chain is used when an end certificate (that is not self-signed) is validated - it must lead to a root certificate that is trusted. More precisely the public key of each CA is used to decode and verify the hash for an issued certificate. This process is repeated until the root certificate is reached. After the whole chain is checked, if the root certificate is trusted the end certificate is also trusted. Of course the process includes other validations too (like start date, end date, certificate revocation list for example), but I have detailed only the part related to the usage of the chain.

So you have correctly imported "My certificate" together with the chain to "Root certificate CA" - this chain is encoded in "My certificate" and you can confirm this by viewing its properties, but this chain is only a link and it does not contain any of "Root certificate CA", "Organization certificate CA" and "Organization 2 certificate CA" certificates.

I hope this solves your issue, but if it doesn't, could you be more specific about what are you trying to accomplish?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!