简体   繁体   中英

Adding TLS certificate to the API request with exception: The request was aborted: Could not create SSL/TLS secure channel

To be able to use some API, I have to use the TLS certificate (in 1.1 version).

My code looks like:

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
{
}

During request.GetResponse() I always get exception: The request was aborted: Could not create SSL/TLS secure channel.

The provider answered me that:

There need be,

Root Ca v1 test.pem in your Truststore and TLSCertificate in your Keystore

Please, advise me what should I do with the file .pem ? It should be added to the request, the same as the TLScertificate.p12 file? When I add second X509Certificate2 (without any password) to the request, I still get the same error.

First, you can use the loaded cert right away to the request

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

The pem file has to be imported into your computers KeyStore mmc -> File -> Add/Remove Snap-in -> Certificates

This can help converting pem to crt Convert .pem to .crt and .key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM