为什么在附加客户端证书时出现"Could not create SSL/TLS secure channel"?



当我的代码试图向服务器发送请求时,我看到了这条消息,该服务器要求请求附带带有私钥的客户端证书(这可能是一种不寻常的情况)。使用通过SoapUI发送的请求,我已经验证了证书是否有效。我的代码是否可能以错误的方式附加证书?

代码看起来是这样的(它可能包含许多在搜索难以捉摸的解决方案时不需要的东西):

// build stuff
var httpClientHandler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
ClientCertificateOptions = ClientCertificateOption.Manual
};
var certificate = new X509Certificate(certName, password, X509KeyStorageFlags.UserKeySet);
httpClientHandler.ClientCertificates.Add(certificate);
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(requestBody, Encoding.UTF8, "application/xml")
};
var httpClient = new HttpClient(httpClientHandler);
httpClient                   
.DefaultRequestHeaders
.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Enable protocols
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
// fire! (here's where the exception is thrown)
var response = await httpClient.SendAsync(request).ConfigureAwait(false);

此实例中的问题在于证书,特别是私钥。

我使用的是.cer证书,它的行为与.pfx文件不同。SoapUI和curl都可以很好地使用.cer,但加载.cer的C#代码会丢失私钥。(为什么我们连接的服务器需要私钥是另一个问题-我的理解是,它不应该-感谢对此的任何想法。)同样,通过MMC管理单元加载到存储的.cer文件也会丢失私钥。我还不知道为什么。

尽管我最初将.pfx文件加载到证书存储中的努力是成功的,但当我开始在另一个帐户下运行应用程序时,返回了"无法创建SSL/TLS安全通道"错误(此处和此处解释)。本质上,证书存储将私钥保存在文件系统位置,只有将证书加载到存储中的用户才能访问该位置。

相反,我直接从文件系统加载证书,如下所示:

var certBytes = File.ReadAllBytes(certFileName);
var certificate = new X509Certificate2(certBytes, password, X509KeyStorageFlags.Exportable);
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ClientCertificates.Add(certificate);
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(requestBody, Encoding.UTF8, "application/xml")
};
var httpClient = new HttpClient(httpClientHandler);
httpClient                   
.DefaultRequestHeaders
.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// fire!
var response = await httpClient.SendAsync(request).ConfigureAwait(false);

最新更新