从商店加载 X509Certificate2 证书链

Loading X509Certificate2 certificate chain from store

我有一个文件 (.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");

certFromStore 应该等同于 clientCert,最后一行让你崩溃。

RawData 属性 X509Certificate2 returns 证书的 DER 编码值,而不是原始文件字节。证书没有私钥,因此最后一行将其删除。您的问题之前提到了 TLS 异常,那是因为您的证书不再有私钥。

如果 certFromStore.HasPrivateKey 为假,那么您将证书放入商店所做的任何操作都不会像您认为的那样起作用。带有私钥的证书在根存储中是很不寻常的。