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

Chl*_*loé 27 c# pfx

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

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

证书已导出

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

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

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

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

Bil*_*gee 47

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

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);
Run Code Online (Sandbox Code Playgroud)

然后你可以遍历集合:

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
}
Run Code Online (Sandbox Code Playgroud)

根据证书类型(客户端证书,中间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证书.