将TLS证书添加到API请求,但异常:请求已中止:无法创建SSL / TLS安全通道

时间:2016-02-01 10:34:23

标签: .net api ssl ssl-certificate x509certificate2

为了能够使用某些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安全通道。

提供者回答我:

  

需要,

     

您的Truststore中的Root Ca v1 test.pem和   密钥库中的TLSCertificate

请告诉我该怎么处理文件.pem?它应该添加到请求中,与TLScertificate.p12文件相同?当我向请求添加第二个X509Certificate2(没有任何密码)时,我仍然会收到相同的错误。

1 个答案:

答案 0 :(得分:0)

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

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

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

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