无法使用证书存储中的客户端证书,只能通过从文件加载

Cannot use client certificate from certificate store, only by loading from file

我正在使用 WebRequest 连接到使用 https 的网页。

如果我尝试使用 LocalMachine 中个人存储中的客户端证书,方法是

var myStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
myStore.Open(OpenFlags.ReadOnly);

var clientCertificates = myStore.Certificates.Find(X509FindType.FindBySubjectName, "foobar",
  validOnly: false);

然后我与

建立连接
var req = (HttpWebRequest)WebRequest.Create("https://theserver.com/the/url");
req.Method = "POST";
req.ContentType = "application/json";
req.ProtocolVersion = HttpVersion.Version11;

req.ClientCertificates = clientCertificates; 

req.ServerCertificateValidationCallback += (o, certificate, chain, errors) =>
{
  return true;
};

using (var stream = req.GetRequestStream())
{
  stream.Write(data, 0, data.Length);
  stream.Flush();
}

var response = req.GetResponse();

我在 req.GetResponse 行失败

System.Net.WebException: 'The request was aborted: Could not create SSL/TLS secure channel.'

但是如果我改为从文件加载客户端证书(与我之前在商店中安装的文件相同)

var certificatePath = @"C:\temp\file.p12";

var clientCertificate = new X509Certificate2(certificatePath, "pwd", 
  X509KeyStorageFlags.Exportable);

req.ClientCertificates.Add(clientCertificate);

我将能够运行 https 查询成功。

这需要我在文件系统中保留一个文件,并在源代码中输入密码。

编辑

访问这些证书(客户端和服务器证书)的首选方法是将它们作为端点放在 web.config 中,但我没有成功。

为了解决 problem/many 问题的症状,我不得不将用户 Everyone 添加到证书私钥的 ACL 中。

我没有更改私钥的 ACL,而是发现如果我只给它 public 密钥,ClientCertificates 属性 工作得很好。是的,如果您在商店中没有私钥,身份验证将无法工作,但转换为 public-key-only 证书似乎每次都对我有用。

var publicKeyOnly = new X509Certificate2(authenticationCert.Export((X509ContentType.Cert));