【问题标题】:Loading X509Certificate2 certificate chain from store从存储加载 X509Certificate2 证书链
【发布时间】:2017-09-02 20:20:10
【问题描述】:

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

【问题讨论】:

  • 如果第一行代表您的代码,那么 clientCert 不是链接 3 个证书,而只是具有私钥的证书。第二行无法产生您显示的错误,因此显然有更多上下文。比如,你是如何获得certFromStore 的。
  • 当我在商店中导入同一个文件时,我得到了 3 个证书,但是当从代码中加载它时,它是一个带有私钥的证书。那么我怎样才能从商店里得到同样的东西呢?这就是我从商店加载它们的方式:var computerCaStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine); computerCaStore.Open(OpenFlags.ReadOnly); var certificates = computerCaStore.Certificates.OfType&lt;X509Certificate2&gt;().ToList(); var clientCertificat1 = certificates.Single(c =&gt; c.Thumbprint == thumbprintMerchant); 我使用指纹
  • 请根据上下文编辑问题。您在评论中的示例代码与问题不匹配,因此很难推理任何事情。
  • @GabrielAndrei 你是怎么解决这个问题的?
  • @GabrielAndrei 我使用了 certFromStore 而不是创建一个新的。它奏效了

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-28
    • 2018-04-01
    • 2018-05-02
    • 2016-10-17
    • 2023-02-13
    • 2022-12-18
    • 2015-07-19
    • 1970-01-01
    相关资源
    最近更新 更多