如何使用c#从pfx文件中检索证书?

我一直在谷歌上搜索半天寻找一种方法来读取.pfx文件并将证书导入certstore

到目前为止,我能够使用X509Certifcate读取.pfx文件,并能够在.pfx文件中导入一个证书。 到目前为止一切顺利,但.pfx文件中有三个证书,当使用X509Certificate加载.pfx时,我无法看到其他两个证书。

证书已导出

*个人信息交流 – PKCS#12(.PFX)

  • 如果可能,请在证书路径中包含所有证书

  • 启用强大保护(需要IE 5.0,NT 4.0 SP4或更高版本)

这些是导出证书时选择的选项。 我知道有三个证书,因为我手动进入certstore(MMC)并自己将其导入个人文件夹。

您应该能够通过使用X509Certificate2Collection类获取包含.pfx文件中的证书的集合对象…这里是一些C#示例代码:

 string certPath = ; string certPass = ; // 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 certificates into X509Store objects } 

根据证书类型(客户端证书,中间CA证书,根CA),您需要打开正确的证书库(作为X509Store对象)来导入它。

查看X509Store文档:

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

StoreName枚举中的不同成员:

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

据我所知,您希望StoreName.My用于包含私钥的客户端证书, StoreName.CertificateAuthority用于中间CA证书, StoreName.Root用于根CA证书。