从商店加载X509Certificate2证书链

时间:2017-04-07 12:33:02

标签: c# .net certificate client-certificates x509certificate2

我有一个文件(.p12)包含3个证书(链接在一起)密码保护,我已经安装在我的商店。 我试图将它们加载到我的代码中。 我从文件加载它们的方式是这样的:

 var clientCert = new X509Certificate2(@"myfile.p12", "mypassword");

如何在从商店加载时获得相同的结果?

我试过了:

var computerCaStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine); 
computerCaStore.Open(OpenFlags.ReadOnly); 
var certificates = computerCaStore.Certificates.OfType<X509Certificate2>().ToLi‌​st(); 
var certFromStore = certificates.Single(c => c.Thumbprint == thumbprintMerchant);
var newCert = new X509Certificate2(certFromStore.RawData, "mypassword");

1 个答案:

答案 0 :(得分:1)

certFromStore应该等同于clientCert,最后一行是打破你的。

RawData上的X509Certificate2属性返回证书的DER编码值,而不是原始文件字节。证书没有私钥,因此最后一行将其剥离。您之前提到的问题是TLS例外,这是因为您的证书不再具有私钥。

如果certFromStore.HasPrivateKey为假,那么您将证书放入商店所做的任何工作都不会像您认为的那样工作。具有私钥的证书位于Root存储区中非常罕见。

相关问题