【问题标题】:Adding TLS certificate to the API request with exception: The request was aborted: Could not create SSL/TLS secure channel向 API 请求添加 TLS 证书时出现异常:请求被中止:无法创建 SSL/TLS 安全通道
【发布时间】:2016-05-09 18:34:25
【问题描述】:

为了能够使用某些 API,我必须使用 TLS 证书(在 1.1 版本中)。

我的代码如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://someapi/request/");

request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = Encoding.UTF8.GetByteCount(postData);
request.KeepAlive = false;

request.ProtocolVersion = HttpVersion.Version11;

ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

X509Certificate2 certificate = new X509Certificate2(@"d:\TLScertificate.p12", "password");  

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

try
{
    store.Open(OpenFlags.ReadWrite);

    if (!store.Certificates.Contains(certificate))
    {
        store.Add(certificate);
    }

    int indexOfCertificate = store.Certificates.IndexOf(certificate);
    certificate = store.Certificates[indexOfCertificate];
}
finally
{
    store.Close();
}

request.ClientCertificates.Add(certificate);
request.PreAuthenticate = true;

using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) // Exception
{
}

request.GetResponse() 期间,我总是遇到异常:请求被中止:无法创建 SSL/TLS 安全通道。

供应商回答我说:

需要,

您的信任库中的根 Ca v1 test.pem 和 密钥库中的 TLSCertificate

请告诉我我应该如何处理文件 .pem ?应该添加到请求中,和TLScertificate.p12文件一样​​吗?当我在请求中添加第二个 X509Certificate2(没有任何密码)时,我仍然得到同样的错误。

【问题讨论】:

    标签: .net api ssl ssl-certificate x509certificate2


    【解决方案1】:

    首先,您可以立即将加载的证书用于请求

       X509Certificate2 certificate = new X509Certificate2(@"d:\TLScertificate.p12", "password");
        request.ClientCertificates.Add(certificate);
    

    必须将 pem 文件导入您的计算机 KeyStore mmc -> 文件 -> 添加/删除管理单元 -> 证书

    这有助于将 pem 转换为 crt Convert .pem to .crt and .key

    【讨论】:

    • 但是当我安装 TLScertificate.p12 时,ROOT CA.pem 也会自动安装,我可以在 mmc 的 Trusted Root Certification Authorities 中看到它。不过,我得到了同样的例外......
    • 试试这个以确保你的机器接受远程证书request.ServerCertificateValidationCallback = certcallback; private static bool certcallback( object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; } 如果在那之后你仍然有问题,你可能得到了一个错误的证书......我有同样的问题。调试了一天...
    • 我加了这个回调,可惜异常是一样的。
    • 对不起...没有线索,但你可以试试这个:stackoverflow.com/questions/5112515/…
    猜你喜欢
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 2021-10-05
    • 2012-06-05
    • 2018-04-22
    • 2012-10-30
    相关资源
    最近更新 更多