Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback - c#

I'm trying to establish SSL/TLS connection to test server with self-signed certificate. Communication through unsecure channel worked without issues.
Here is my sample code, which I've written based on this solutions:
Allowing Untrusted SSL Certificates with HttpClient
C# Ignore certificate errors?
.NET client connecting to ssl Web API
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
var c = new HttpClient();
var r = c.GetAsync("https://10.3.0.1:8443/rest/v1").Result;
if (r.IsSuccessStatusCode)
{
Log.AddMessage(r.Content.Get<string>());
}
else
{
Log.AddMessage(string.Format("{0} ({1})", (int)r.StatusCode, r.ReasonPhrase));
}
also tried this:
var handler = new WebRequestHandler();
handler.ServerCertificateValidationCallback = delegate { return true; };
var c = new HttpClient(handler);
...
and this
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
but each time I've got an exception:
InnerException: System.Net.Http.HttpRequestException
_HResult=-2146233088
_message=An error occurred while sending the request.
HResult=-2146233088
IsTransient=false
Message=An error occurred while sending the request.
InnerException: System.Net.WebException
_HResult=-2146233079
_message=The request was aborted: Could not create SSL/TLS secure channel.
HResult=-2146233079
IsTransient=false
Message=The request was aborted: Could not create SSL/TLS secure channel.
Source=System
StackTrace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
InnerException:
What do I do wrong? Why I can't connect to this server (which has invalid-self-signed certificate)

You are doing it right with ServerCertificateValidationCallback. This is not the problem you are facing. The problem you are facing is most likely the version of SSL/TLS protocol.
For example, if your server offers only SSLv3 and TLSv10 and your client needs TLSv12 then you will receive this error message. What you need to do is to make sure that both client and server have a common protocol version supported.
When I need a client that is able to connect to as many servers as possible (rather than to be as secure as possible) I use this (together with setting the validation callback):
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

We have been solving the same problem just today, and all you need to do is to increase the runtime version of .NET
4.5.2 didn't work for us with the above problem, while 4.6.1 was OK
If you need to keep the .NET version, then set
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Just as a follow up for anyone still running into this – I had added the ServicePointManager.SecurityProfile options as noted in the solution:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
And yet I continued to get the same “The request was aborted: Could not create SSL/TLS secure channel” error. I was attempting to connect to some older voice servers with HTTPS SOAP API interfaces (i.e. voice mail, IP phone systems etc… installed years ago). These only support SSL3 connections as they were last updated years ago.
One would think including SSl3 in the list of SecurityProtocols would do the trick here, but it didn’t. The only way I could force the connection was to include ONLY the Ssl3 protocol and no others:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Then the connection goes through – seems like a bug to me but this didn’t start throwing errors until recently on tools I provide for these servers that have been out there for years – I believe Microsoft has started rolling out system changes that have updated this behavior to force TLS connections unless there is no other alternative.
Anyway – if you’re still running into this against some old sites/servers, it’s worth giving it a try.

move this line: ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Before this line: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
Original post: KB4344167 security update breaks TLS Code

In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.

TLS 1.0 and 1.1 are now End of Life. A package on our Amazon web server updated, and we started getting this error.
The answer is above, but you shouldn't use tls or tls11 anymore.
Specifically for ASP.Net, add this to one of your startup methods.
public Startup()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
but I'm sure that something like this will work in many other cases.

I'm using .NET version 4.8 and specifying the SSL protocol during the initialization of the HttpClient worked for me to resolve this issue, as shown below.
var client = new HttpClient(new HttpClientHandler { SslProtocols = SslProtocols.Tls12});

I came across this thread because I also had the error Could not create SSL/TLS secure channel. In my case, I was attempting to access a Siebel configuration REST API from PowerShell using Invoke-RestMethod, and none of the suggestions above helped.
Eventually I stumbled across the cause of my problem: the server I was contacting required client certificate authentication.
To make the calls work, I had to provide the client certificate (including the private key) with the -Certificate parameter:
$Pwd = 'certificatepassword'
$Pfx = New-Object -TypeName 'System.Security.Cryptography.X509Certificates.X509Certificate2'
$Pfx.Import('clientcert.p12', $Pwd, 'Exportable,PersistKeySet')
Invoke-RestMethod -Uri 'https://your.rest.host/api/' -Certificate $Pfx -OtherParam ...
Hopefully my experience might help someone else who has my particular flavour of this problem.

If will work perfect if you specify only TLS in security protocol.
try {
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = delegate {
return true;
};
var webClient = new WebClient();
var s = webClient.DownloadString("https://google.com");
Console.WriteLine(s);
} catch (Exception ex) {
Console.WriteLine(ex);
}
Console.ReadLine();

If you are using a new domain name, and you have done all the above and you are still getting the same error, check to see if you clear the DNS cache on your PC.
Clear your DNS for more details.
Windows® 8
To clear your DNS cache if you use Windows 8, perform the following steps:
On your keyboard, press Win+X to open the WinX Menu.
Right-click Command Prompt and select Run as Administrator.
Run the following command:
ipconfig /flushdns
If the command succeeds, the system returns the following message:
Windows IP configuration successfully flushed the DNS Resolver Cache.
Windows® 7
To clear your DNS cache if you use Windows 7, perform the following steps:
Click Start.
Enter cmd in the Start menu search text box.
Right-click Command Prompt and select Run as Administrator.
Run the following command:
ipconfig /flushdns
If the command succeeds, the system returns the following message:
Windows IP configuration successfully flushed the DNS Resolver Cache.

Related

C# HttpRequestException when doing web calls inside a VM [duplicate]

We are unable to connect to an HTTPS server using WebRequest because of this error message:
The request was aborted: Could not create SSL/TLS secure channel.
We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:
private void Somewhere() {
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}
private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
return true;
}
The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?
I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP. Does that change something?
I finally found the answer (I haven't noted my source but it was from a search);
While the code works in Windows XP, in Windows 7, you must add this at the beginning:
// using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons
And now, it works perfectly.
ADDENDUM
As mentioned by Robin French; if you are getting this problem while configuring PayPal, please note that they won't support SSL3 starting by December, 3rd 2018. You'll need to use TLS. Here's Paypal page about it.
The solution to this, in .NET 4.5 is
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
If you don’t have .NET 4.5 then use
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
Make sure the ServicePointManager settings are made before the HttpWebRequest is created, else it will not work.
Works:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
Fails:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
Note: Several of the highest voted answers here advise setting ServicePointManager.SecurityProtocol, but Microsoft explicitly advises against doing that. Below, I go into the typical cause of this issue and the best practices for resolving it.
One of the biggest causes of this issue is the active .NET Framework version. The .NET framework runtime version affects which security protocols are enabled by default.
In ASP.NET sites, the framework runtime version is often specified in web.config. (see below)
In other apps, the runtime version is usually the version for which the project was built, regardless of whether it is running on a machine with a newer .NET version.
There doesn't seem to be any authoritative documentation on how it specifically works in different versions, but it seems the defaults are determined more or less as follows:
Framework Version
Default Protocols
4.5 and earlier
SSL 3.0, TLS 1.0
4.6.x
TLS 1.0, 1.1, 1.2, 1.3
4.7+
System (OS) Defaults
For the older versions, your mileage may vary somewhat based on which .NET runtimes are installed on the system. For example, there could be a situation where you are using a very old framework and TLS 1.0 is not supported, or using 4.6.x and TLS 1.3 is not supported.
Microsoft's documentation strongly advises using 4.7+ and the system defaults:
We recommend that you:
Target .NET Framework 4.7 or later versions on your apps. Target .NET Framework 4.7.1 or later versions on your WCF apps.
Do not specify the TLS version. Configure your code to let the OS decide on the TLS version.
Perform a thorough code audit to verify you're not specifying a TLS or SSL version.
For ASP.NET sites: check the targetFramework version in your <httpRuntime> element, as this (when present) determines which runtime is actually used by your site:
<httpRuntime targetFramework="4.5" />
Better:
<httpRuntime targetFramework="4.7" />
I had this problem trying to hit https://ct.mob0.com/Styles/Fun.png, which is an image distributed by CloudFlare on its CDN that supports crazy stuff like SPDY and weird redirect SSL certs.
Instead of specifying Ssl3 as in Simons answer I was able to fix it by going down to Tls12 like this:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
new WebClient().DownloadData("https://ct.mob0.com/Styles/Fun.png");
The problem you're having is that the aspNet user doesn't have access to the certificate. You have to give access using the winhttpcertcfg.exe
An example on how to set this up is at:
http://support.microsoft.com/kb/901183
Under step 2 in more information
EDIT: In more recent versions of IIS, this feature is built in to the certificate manager tool - and can be accessed by right clicking on the certificate and using the option for managing private keys. More details here: https://serverfault.com/questions/131046/how-to-grant-iis-7-5-access-to-a-certificate-in-certificate-store/132791#132791
After many long hours with this same issue I found that the ASP.NET account the client service was running under didn't have access to the certificate. I fixed it by going into the IIS Application Pool that the web app runs under, going into Advanced Settings, and changing the Identity to the LocalSystem account from NetworkService.
A better solution is to get the certificate working with the default NetworkService account but this works for quick functional testing.
The error is generic and there are many reasons why the SSL/TLS negotiation may fail. The most common is an invalid or expired server certificate, and you took care of that by providing your own server certificate validation hook, but is not necessarily the only reason. The server may require mutual authentication, it may be configured with a suites of ciphers not supported by your client, it may have a time drift too big for the handshake to succeed and many more reasons.
The best solution is to use the SChannel troubleshooting tools set. SChannel is the SSPI provider responsible for SSL and TLS and your client will use it for the handshake. Take a look at TLS/SSL Tools and Settings.
Also see How to enable Schannel event logging.
The approach with setting
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Seems to be okay, because Tls1.2 is latest version of secure protocol. But I decided to look deeper and answer do we really need to hardcode it.
Specs: Windows Server 2012R2 x64.
From the internet there is told that .NetFramework 4.6+ must use Tls1.2 by default. But when I updated my project to 4.6 nothing happened.
I have found some info that tells I need manually do some changes to enable Tls1.2 by default
https://support.microsoft.com/en-in/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi
But proposed windows update doesnt work for R2 version
But what helped me is adding 2 values to registry. You can use next PS script so they will be added automatically
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
That is kind of what I was looking for. But still I cant answer on question why NetFramework 4.6+ doesn't set this ...Protocol value automatically?
Another possible cause of the The request was aborted: Could not create SSL/TLS secure channel error is a mismatch between your client PC's configured cipher_suites values, and the values that the server is configured as being willing and able to accept. In this case, when your client sends the list of cipher_suites values that it is able to accept in its initial SSL handshaking/negotiation "Client Hello" message, the server sees that none of the provided values are acceptable, and may return an "Alert" response instead of proceeding to the "Server Hello" step of the SSL handshake.
To investigate this possibility, you can download Microsoft Message Analyzer, and use it to run a trace on the SSL negotiation that occurs when you try and fail to establish an HTTPS connection to the server (in your C# app).
If you are able to make a successful HTTPS connection from another environment (e.g. the Windows XP machine that you mentioned -- or possibly by hitting the HTTPS URL in a non-Microsoft browser that doesn't use the OS's cipher suite settings, such as Chrome or Firefox), run another Message Analyzer trace in that environment to capture what happens when the SSL negotiation succeeds.
Hopefully, you'll see some difference between the two Client Hello messages that will allow you to pinpoint exactly what about the failing SSL negotiation is causing it to fail. Then you should be able to make configuration changes to Windows that will allow it to succeed. IISCrypto is a great tool to use for this (even for client PCs, despite the "IIS" name).
The following two Windows registry keys govern the cipher_suites values that your PC will use:
HKLM\SOFTWARE\Policies\Microsoft\Cryptography\Configuration\SSL\00010002
HKLM\SYSTEM\CurrentControlSet\Control\Cryptography\Configuration\Local\SSL\00010002
Here's a full writeup of how I investigated and solved an instance of this variety of the Could not create SSL/TLS secure channel problem: http://blog.jonschneider.com/2016/08/fix-ssl-handshaking-error-in-windows.html
Something the original answer didn't have. I added some more code to make it bullet proof.
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
The top-voted answer will probably be enough for most people. However, in some circumstances, you could continue getting a "Could not create SSL/TLS secure channel" error even after forcing TLS 1.2. If so, you may want to consult this helpful article for additional troubleshooting steps. To summarize: independent of the TLS/SSL version issue, the client and server must agree on a "cipher suite." During the "handshake" phase of the SSL connection, the client will list its supported cipher-suites for the server to check against its own list. But on some Windows machines, certain common cipher-suites may have been disabled (seemingly due to well-intentioned attempts to limit attack surface), decreasing the possibility of the client & server agreeing on a cipher suite. If they cannot agree, then you may see "fatal alert code 40" in the event viewer and "Could not create SSL/TLS secure channel" in your .NET program.
The aforementioned article explains how to list all of a machine's potentially-supported cipher suites and enable additional cipher suites through the Windows Registry. To help check which cipher suites are enabled on the client, try visiting this diagnostic page in MSIE. (Using System.Net tracing may give more definitive results.) To check which cipher suites are supported by the server, try this online tool (assuming that the server is Internet-accessible). It should go without saying that Registry edits must be done with caution, especially where networking is involved. (Is your machine a remote-hosted VM? If you were to break networking, would the VM be accessible at all?)
In my company's case, we enabled several additional "ECDHE_ECDSA" suites via Registry edit, to fix an immediate problem and guard against future problems. But if you cannot (or will not) edit the Registry, then numerous workarounds (not necessarily pretty) come to mind. For example: your .NET program could delegate its SSL traffic to a separate Python program (which may itself work, for the same reason that Chrome requests may succeed where MSIE requests fail on an affected machine).
This one is working for me in MVC webclient
public string DownloadSite(string RefinedLink)
{
try
{
Uri address = new Uri(RefinedLink);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
using (WebClient webClient = new WebClient())
{
var stream = webClient.OpenRead(address);
using (StreamReader sr = new StreamReader(stream))
{
var page = sr.ReadToEnd();
return page;
}
}
}
catch (Exception e)
{
log.Error("DownloadSite - error Lin = " + RefinedLink, e);
return null;
}
}
"The request was aborted: Could not create SSL/TLS secure channel" exception can occur if the server is returning an HTTP 401 Unauthorized response to the HTTP request.
You can determine if this is happening by turning on trace-level System.Net logging for your client application, as described in this answer.
Once that logging configuration is in place, run the application and reproduce the error, then look in the logging output for a line like this:
System.Net Information: 0 : [9840] Connection#62912200 - Received status line: Version=1.1, StatusCode=401, StatusDescription=Unauthorized.
In my situation, I was failing to set a particular cookie that the server was expecting, leading to the server responding to the request with the 401 error, which in turn led to the "Could not create SSL/TLS secure channel" exception.
Another possibility is improper certificate importation on the box. Make sure to select encircled check box. Initially I didn't do it, so code was either timing out or throwing same exception as private key could not be located.
I had this problem because my web.config had:
<httpRuntime targetFramework="4.5.2" />
and not:
<httpRuntime targetFramework="4.6.1" />
Doing this helped me:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Finally found solution for me.
Try this adding below line before calling https url (for .Net framework 4.5):
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
As you can tell there are plenty of reasons this might happen. Thought I would add the cause I encountered ...
If you set the value of WebRequest.Timeout to 0, this is the exception that is thrown. Below is the code I had... (Except instead of a hard-coded 0 for the timeout value, I had a parameter which was inadvertently set to 0).
WebRequest webRequest = WebRequest.Create(#"https://myservice/path");
webRequest.ContentType = "text/html";
webRequest.Method = "POST";
string body = "...";
byte[] bytes = Encoding.ASCII.GetBytes(body);
webRequest.ContentLength = bytes.Length;
var os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
webRequest.Timeout = 0; //setting the timeout to 0 causes the request to fail
WebResponse webResponse = webRequest.GetResponse(); //Exception thrown here ...
The root of this exception in my case was that at some point in code the following was being called:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
This is really bad. Not only is it instructing .NET to use an insecure protocol, but this impacts every new WebClient (and similar) request made afterward within your appdomain. (Note that incoming web requests are unaffected in your ASP.NET app, but new WebClient requests, such as to talk to an external web service, are).
In my case, it was not actually needed, so I could just delete the statement and all my other web requests started working fine again. Based on my reading elsewhere, I learned a few things:
This is a global setting in your appdomain, and if you have concurrent activity, you can't reliably set it to one value, do your action, and then set it back. Another action may take place during that small window and be impacted.
The correct setting is to leave it default. This allows .NET to continue to use whatever is the most secure default value as time goes on and you upgrade frameworks. Setting it to TLS12 (which is the most secure as of this writing) will work now but in 5 years may start causing mysterious problems.
If you really need to set a value, you should consider doing it in a separate specialized application or appdomain and find a way to talk between it and your main pool. Because it's a single global value, trying to manage it within a busy app pool will only lead to trouble. This answer: https://stackoverflow.com/a/26754917/7656 provides a possible solution by way of a custom proxy. (Note I have not personally implemented it.)
In my case, the service account running the application did not have permission to access the private key. Once I gave this permission, the error went away
mmc
certificates
Expand to personal
select cert
right click
All tasks
Manage private keys
Add the service account user
If you are running your code from Visual Studio, try running Visual Studio as administrator. Fixed the issue for me.
System.Net.WebException: The request was aborted: Could not create
SSL/TLS secure channel.
In our case, we where using a software vendor so we didn't have access to modify the .NET code. Apparently .NET 4 won't use TLS v 1.2 unless there is a change.
The fix for us was adding the SchUseStrongCrypto key to the registry. You can copy/paste the below code into a text file with the .reg extension and execute it. It served as our "patch" to the problem.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
I have struggled with this problem all day.
When I created a new project with .NET 4.5 I finally got it to work.
But if I downgraded to 4.0 I got the same problem again, and it was irreversable for that project (even when i tried to upgrade to 4.5 again).
Strange no other error message but "The request was aborted: Could not create SSL/TLS secure channel." came up for this error
In case that the client is a windows machine, a possible reason could be that the tls or ssl protocol required by the service is not activated.
This can be set in:
Control Panel -> Network and Internet -> Internet Options -> Advanced
Scroll settings down to "Security" and choose between
Use SSL 2.0
Use SSL 3.0
Use TLS 1.0
Use TLS 1.1
Use TLS 1.2
none of this answer not working for me , the google chrome and postman work and handshake the server but ie and .net not working. in google chrome in security tab > connection show that encrypted and authenticated using ECDHE_RSA with P-256 and AES_256_GCM cipher suite to handshake with the server.
i install IIS Crypto and in cipher suites list on windows server 2012 R2 ican't find ECDHE_RSA with P-256 and AES_256_GCM cipher suite. then i update windows to the last version but the problem not solve. finally after searches i understood that windows server 2012 R2 not support GSM correctly and update my server to windows server 2016 and my problem solved.
I was having this same issue and found this answer worked properly for me. The key is 3072. This link provides the details on the '3072' fix.
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
XmlReader r = XmlReader.Create(url);
SyndicationFeed albums = SyndicationFeed.Load(r);
In my case two feeds required the fix:
https://www.fbi.gov/feeds/fbi-in-the-news/atom.xml
https://www.wired.com/feed/category/gear/latest/rss
None of the answers worked for me.
This is what worked:
Instead of initializing my X509Certifiacte2 like this:
var certificate = new X509Certificate2(bytes, pass);
I did it like this:
var certificate = new X509Certificate2(bytes, pass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
Notice the X509KeyStorageFlags.Exportable !!
I didn't change the rest of the code (the WebRequest itself):
// I'm not even sure the first two lines are necessary:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
request = (HttpWebRequest)WebRequest.Create(string.Format("https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", server));
request.Method = "GET";
request.Referer = string.Format("https://hercules.sii.cl/cgi_AUT2000/autInicio.cgi?referencia=https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", servidor);
request.UserAgent = "Mozilla/4.0";
request.ClientCertificates.Add(certificate);
request.CookieContainer = new CookieContainer();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// etc...
}
In fact I'm not even sure that the first two lines are necessary...
Another possibility is that the code being executed doesn't have the required permissions.
In my case, I got this error when using Visual Studio debugger to test a call to a web service. Visual Studio wasn't running as Administrator, which caused this exception.
This fixed for me, add Network Service to permissions.
Right click on the certificate > All Tasks > Manage Private Keys... > Add... > Add "Network Service".

The request was aborted: Could not create SSL/TLS secure channel on host, local run fine [duplicate]

We are unable to connect to an HTTPS server using WebRequest because of this error message:
The request was aborted: Could not create SSL/TLS secure channel.
We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:
private void Somewhere() {
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}
private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
return true;
}
The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?
I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP. Does that change something?
I finally found the answer (I haven't noted my source but it was from a search);
While the code works in Windows XP, in Windows 7, you must add this at the beginning:
// using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons
And now, it works perfectly.
ADDENDUM
As mentioned by Robin French; if you are getting this problem while configuring PayPal, please note that they won't support SSL3 starting by December, 3rd 2018. You'll need to use TLS. Here's Paypal page about it.
The solution to this, in .NET 4.5 is
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
If you don’t have .NET 4.5 then use
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
Make sure the ServicePointManager settings are made before the HttpWebRequest is created, else it will not work.
Works:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
Fails:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
Note: Several of the highest voted answers here advise setting ServicePointManager.SecurityProtocol, but Microsoft explicitly advises against doing that. Below, I go into the typical cause of this issue and the best practices for resolving it.
One of the biggest causes of this issue is the active .NET Framework version. The .NET framework runtime version affects which security protocols are enabled by default.
In ASP.NET sites, the framework runtime version is often specified in web.config. (see below)
In other apps, the runtime version is usually the version for which the project was built, regardless of whether it is running on a machine with a newer .NET version.
There doesn't seem to be any authoritative documentation on how it specifically works in different versions, but it seems the defaults are determined more or less as follows:
Framework Version
Default Protocols
4.5 and earlier
SSL 3.0, TLS 1.0
4.6.x
TLS 1.0, 1.1, 1.2, 1.3
4.7+
System (OS) Defaults
For the older versions, your mileage may vary somewhat based on which .NET runtimes are installed on the system. For example, there could be a situation where you are using a very old framework and TLS 1.0 is not supported, or using 4.6.x and TLS 1.3 is not supported.
Microsoft's documentation strongly advises using 4.7+ and the system defaults:
We recommend that you:
Target .NET Framework 4.7 or later versions on your apps. Target .NET Framework 4.7.1 or later versions on your WCF apps.
Do not specify the TLS version. Configure your code to let the OS decide on the TLS version.
Perform a thorough code audit to verify you're not specifying a TLS or SSL version.
For ASP.NET sites: check the targetFramework version in your <httpRuntime> element, as this (when present) determines which runtime is actually used by your site:
<httpRuntime targetFramework="4.5" />
Better:
<httpRuntime targetFramework="4.7" />
I had this problem trying to hit https://ct.mob0.com/Styles/Fun.png, which is an image distributed by CloudFlare on its CDN that supports crazy stuff like SPDY and weird redirect SSL certs.
Instead of specifying Ssl3 as in Simons answer I was able to fix it by going down to Tls12 like this:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
new WebClient().DownloadData("https://ct.mob0.com/Styles/Fun.png");
The problem you're having is that the aspNet user doesn't have access to the certificate. You have to give access using the winhttpcertcfg.exe
An example on how to set this up is at:
http://support.microsoft.com/kb/901183
Under step 2 in more information
EDIT: In more recent versions of IIS, this feature is built in to the certificate manager tool - and can be accessed by right clicking on the certificate and using the option for managing private keys. More details here: https://serverfault.com/questions/131046/how-to-grant-iis-7-5-access-to-a-certificate-in-certificate-store/132791#132791
After many long hours with this same issue I found that the ASP.NET account the client service was running under didn't have access to the certificate. I fixed it by going into the IIS Application Pool that the web app runs under, going into Advanced Settings, and changing the Identity to the LocalSystem account from NetworkService.
A better solution is to get the certificate working with the default NetworkService account but this works for quick functional testing.
The error is generic and there are many reasons why the SSL/TLS negotiation may fail. The most common is an invalid or expired server certificate, and you took care of that by providing your own server certificate validation hook, but is not necessarily the only reason. The server may require mutual authentication, it may be configured with a suites of ciphers not supported by your client, it may have a time drift too big for the handshake to succeed and many more reasons.
The best solution is to use the SChannel troubleshooting tools set. SChannel is the SSPI provider responsible for SSL and TLS and your client will use it for the handshake. Take a look at TLS/SSL Tools and Settings.
Also see How to enable Schannel event logging.
The approach with setting
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Seems to be okay, because Tls1.2 is latest version of secure protocol. But I decided to look deeper and answer do we really need to hardcode it.
Specs: Windows Server 2012R2 x64.
From the internet there is told that .NetFramework 4.6+ must use Tls1.2 by default. But when I updated my project to 4.6 nothing happened.
I have found some info that tells I need manually do some changes to enable Tls1.2 by default
https://support.microsoft.com/en-in/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi
But proposed windows update doesnt work for R2 version
But what helped me is adding 2 values to registry. You can use next PS script so they will be added automatically
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
That is kind of what I was looking for. But still I cant answer on question why NetFramework 4.6+ doesn't set this ...Protocol value automatically?
Another possible cause of the The request was aborted: Could not create SSL/TLS secure channel error is a mismatch between your client PC's configured cipher_suites values, and the values that the server is configured as being willing and able to accept. In this case, when your client sends the list of cipher_suites values that it is able to accept in its initial SSL handshaking/negotiation "Client Hello" message, the server sees that none of the provided values are acceptable, and may return an "Alert" response instead of proceeding to the "Server Hello" step of the SSL handshake.
To investigate this possibility, you can download Microsoft Message Analyzer, and use it to run a trace on the SSL negotiation that occurs when you try and fail to establish an HTTPS connection to the server (in your C# app).
If you are able to make a successful HTTPS connection from another environment (e.g. the Windows XP machine that you mentioned -- or possibly by hitting the HTTPS URL in a non-Microsoft browser that doesn't use the OS's cipher suite settings, such as Chrome or Firefox), run another Message Analyzer trace in that environment to capture what happens when the SSL negotiation succeeds.
Hopefully, you'll see some difference between the two Client Hello messages that will allow you to pinpoint exactly what about the failing SSL negotiation is causing it to fail. Then you should be able to make configuration changes to Windows that will allow it to succeed. IISCrypto is a great tool to use for this (even for client PCs, despite the "IIS" name).
The following two Windows registry keys govern the cipher_suites values that your PC will use:
HKLM\SOFTWARE\Policies\Microsoft\Cryptography\Configuration\SSL\00010002
HKLM\SYSTEM\CurrentControlSet\Control\Cryptography\Configuration\Local\SSL\00010002
Here's a full writeup of how I investigated and solved an instance of this variety of the Could not create SSL/TLS secure channel problem: http://blog.jonschneider.com/2016/08/fix-ssl-handshaking-error-in-windows.html
Something the original answer didn't have. I added some more code to make it bullet proof.
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
The top-voted answer will probably be enough for most people. However, in some circumstances, you could continue getting a "Could not create SSL/TLS secure channel" error even after forcing TLS 1.2. If so, you may want to consult this helpful article for additional troubleshooting steps. To summarize: independent of the TLS/SSL version issue, the client and server must agree on a "cipher suite." During the "handshake" phase of the SSL connection, the client will list its supported cipher-suites for the server to check against its own list. But on some Windows machines, certain common cipher-suites may have been disabled (seemingly due to well-intentioned attempts to limit attack surface), decreasing the possibility of the client & server agreeing on a cipher suite. If they cannot agree, then you may see "fatal alert code 40" in the event viewer and "Could not create SSL/TLS secure channel" in your .NET program.
The aforementioned article explains how to list all of a machine's potentially-supported cipher suites and enable additional cipher suites through the Windows Registry. To help check which cipher suites are enabled on the client, try visiting this diagnostic page in MSIE. (Using System.Net tracing may give more definitive results.) To check which cipher suites are supported by the server, try this online tool (assuming that the server is Internet-accessible). It should go without saying that Registry edits must be done with caution, especially where networking is involved. (Is your machine a remote-hosted VM? If you were to break networking, would the VM be accessible at all?)
In my company's case, we enabled several additional "ECDHE_ECDSA" suites via Registry edit, to fix an immediate problem and guard against future problems. But if you cannot (or will not) edit the Registry, then numerous workarounds (not necessarily pretty) come to mind. For example: your .NET program could delegate its SSL traffic to a separate Python program (which may itself work, for the same reason that Chrome requests may succeed where MSIE requests fail on an affected machine).
This one is working for me in MVC webclient
public string DownloadSite(string RefinedLink)
{
try
{
Uri address = new Uri(RefinedLink);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
using (WebClient webClient = new WebClient())
{
var stream = webClient.OpenRead(address);
using (StreamReader sr = new StreamReader(stream))
{
var page = sr.ReadToEnd();
return page;
}
}
}
catch (Exception e)
{
log.Error("DownloadSite - error Lin = " + RefinedLink, e);
return null;
}
}
"The request was aborted: Could not create SSL/TLS secure channel" exception can occur if the server is returning an HTTP 401 Unauthorized response to the HTTP request.
You can determine if this is happening by turning on trace-level System.Net logging for your client application, as described in this answer.
Once that logging configuration is in place, run the application and reproduce the error, then look in the logging output for a line like this:
System.Net Information: 0 : [9840] Connection#62912200 - Received status line: Version=1.1, StatusCode=401, StatusDescription=Unauthorized.
In my situation, I was failing to set a particular cookie that the server was expecting, leading to the server responding to the request with the 401 error, which in turn led to the "Could not create SSL/TLS secure channel" exception.
Another possibility is improper certificate importation on the box. Make sure to select encircled check box. Initially I didn't do it, so code was either timing out or throwing same exception as private key could not be located.
I had this problem because my web.config had:
<httpRuntime targetFramework="4.5.2" />
and not:
<httpRuntime targetFramework="4.6.1" />
Doing this helped me:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Finally found solution for me.
Try this adding below line before calling https url (for .Net framework 4.5):
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
As you can tell there are plenty of reasons this might happen. Thought I would add the cause I encountered ...
If you set the value of WebRequest.Timeout to 0, this is the exception that is thrown. Below is the code I had... (Except instead of a hard-coded 0 for the timeout value, I had a parameter which was inadvertently set to 0).
WebRequest webRequest = WebRequest.Create(#"https://myservice/path");
webRequest.ContentType = "text/html";
webRequest.Method = "POST";
string body = "...";
byte[] bytes = Encoding.ASCII.GetBytes(body);
webRequest.ContentLength = bytes.Length;
var os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
webRequest.Timeout = 0; //setting the timeout to 0 causes the request to fail
WebResponse webResponse = webRequest.GetResponse(); //Exception thrown here ...
The root of this exception in my case was that at some point in code the following was being called:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
This is really bad. Not only is it instructing .NET to use an insecure protocol, but this impacts every new WebClient (and similar) request made afterward within your appdomain. (Note that incoming web requests are unaffected in your ASP.NET app, but new WebClient requests, such as to talk to an external web service, are).
In my case, it was not actually needed, so I could just delete the statement and all my other web requests started working fine again. Based on my reading elsewhere, I learned a few things:
This is a global setting in your appdomain, and if you have concurrent activity, you can't reliably set it to one value, do your action, and then set it back. Another action may take place during that small window and be impacted.
The correct setting is to leave it default. This allows .NET to continue to use whatever is the most secure default value as time goes on and you upgrade frameworks. Setting it to TLS12 (which is the most secure as of this writing) will work now but in 5 years may start causing mysterious problems.
If you really need to set a value, you should consider doing it in a separate specialized application or appdomain and find a way to talk between it and your main pool. Because it's a single global value, trying to manage it within a busy app pool will only lead to trouble. This answer: https://stackoverflow.com/a/26754917/7656 provides a possible solution by way of a custom proxy. (Note I have not personally implemented it.)
In my case, the service account running the application did not have permission to access the private key. Once I gave this permission, the error went away
mmc
certificates
Expand to personal
select cert
right click
All tasks
Manage private keys
Add the service account user
If you are running your code from Visual Studio, try running Visual Studio as administrator. Fixed the issue for me.
System.Net.WebException: The request was aborted: Could not create
SSL/TLS secure channel.
In our case, we where using a software vendor so we didn't have access to modify the .NET code. Apparently .NET 4 won't use TLS v 1.2 unless there is a change.
The fix for us was adding the SchUseStrongCrypto key to the registry. You can copy/paste the below code into a text file with the .reg extension and execute it. It served as our "patch" to the problem.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
I have struggled with this problem all day.
When I created a new project with .NET 4.5 I finally got it to work.
But if I downgraded to 4.0 I got the same problem again, and it was irreversable for that project (even when i tried to upgrade to 4.5 again).
Strange no other error message but "The request was aborted: Could not create SSL/TLS secure channel." came up for this error
In case that the client is a windows machine, a possible reason could be that the tls or ssl protocol required by the service is not activated.
This can be set in:
Control Panel -> Network and Internet -> Internet Options -> Advanced
Scroll settings down to "Security" and choose between
Use SSL 2.0
Use SSL 3.0
Use TLS 1.0
Use TLS 1.1
Use TLS 1.2
none of this answer not working for me , the google chrome and postman work and handshake the server but ie and .net not working. in google chrome in security tab > connection show that encrypted and authenticated using ECDHE_RSA with P-256 and AES_256_GCM cipher suite to handshake with the server.
i install IIS Crypto and in cipher suites list on windows server 2012 R2 ican't find ECDHE_RSA with P-256 and AES_256_GCM cipher suite. then i update windows to the last version but the problem not solve. finally after searches i understood that windows server 2012 R2 not support GSM correctly and update my server to windows server 2016 and my problem solved.
I was having this same issue and found this answer worked properly for me. The key is 3072. This link provides the details on the '3072' fix.
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
XmlReader r = XmlReader.Create(url);
SyndicationFeed albums = SyndicationFeed.Load(r);
In my case two feeds required the fix:
https://www.fbi.gov/feeds/fbi-in-the-news/atom.xml
https://www.wired.com/feed/category/gear/latest/rss
None of the answers worked for me.
This is what worked:
Instead of initializing my X509Certifiacte2 like this:
var certificate = new X509Certificate2(bytes, pass);
I did it like this:
var certificate = new X509Certificate2(bytes, pass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
Notice the X509KeyStorageFlags.Exportable !!
I didn't change the rest of the code (the WebRequest itself):
// I'm not even sure the first two lines are necessary:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
request = (HttpWebRequest)WebRequest.Create(string.Format("https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", server));
request.Method = "GET";
request.Referer = string.Format("https://hercules.sii.cl/cgi_AUT2000/autInicio.cgi?referencia=https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", servidor);
request.UserAgent = "Mozilla/4.0";
request.ClientCertificates.Add(certificate);
request.CookieContainer = new CookieContainer();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// etc...
}
In fact I'm not even sure that the first two lines are necessary...
Another possibility is that the code being executed doesn't have the required permissions.
In my case, I got this error when using Visual Studio debugger to test a call to a web service. Visual Studio wasn't running as Administrator, which caused this exception.
This fixed for me, add Network Service to permissions.
Right click on the certificate > All Tasks > Manage Private Keys... > Add... > Add "Network Service".

System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel

I have a windows service in a VM. It is calling an API hosted in another server. When I call that api from my windows service, it is giving me error saying :
System.Net.WebException: The underlying connection was closed: Could
not establish trust relationship for the SSL/TLS secure channel. --->
System.Security.Authentication.AuthenticationException: The remote
certificate is invalid according to the validation procedure.
Now I know that if I add this line before calling the api, it will work fine.
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
But I do not want to change my code and deploy it again. Is there any way I can do something in the VM where windows service is hosted, like trusting the certificate or something , which will resolve this?
Any help in this regard is really helpful. Thanks.
I know this question is asked multiple time, but all the solutions require me to either change in the server where api is hosted or change my code to add above line. I'm looking for a solution where I can change in the client machine rather than anywhere else.
I ran into this a few times. It could mean a few things:
Unsupported protocol(s) (SSL/TSL)
No matching cipher(s)
.NET Framework version < 4.6.1 needs special code
For the first two options, you could use nmap to determine the server's supported list of protocols and ciphers:
nmap -sV --script ssl-enum-ciphers -p 443 <host>
Once having the list of supported protocols/ciphers, you can then check your own on your client machine using a free tool called IISCrypto and verify that you have enabled matching protocol/cipher combinations.
For the last option, if you are running anything less than .NET Framework 4.6.1, you may need to add:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
I don't really suggest setting the protocols strictly as above (since TLS 1.3 is around the corner). Should always try to let windows determine the highest security for you. Sometimes certain evils are necessary to move forward. You can always revisit it later.
This has helped me solve this particular problem. Hopefully it will aid you with yours.

Issue with sending API request over Https - Could not create SSL/TLS secure channel [duplicate]

We are unable to connect to an HTTPS server using WebRequest because of this error message:
The request was aborted: Could not create SSL/TLS secure channel.
We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:
private void Somewhere() {
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}
private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
return true;
}
The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?
I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP. Does that change something?
I finally found the answer (I haven't noted my source but it was from a search);
While the code works in Windows XP, in Windows 7, you must add this at the beginning:
// using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons
And now, it works perfectly.
ADDENDUM
As mentioned by Robin French; if you are getting this problem while configuring PayPal, please note that they won't support SSL3 starting by December, 3rd 2018. You'll need to use TLS. Here's Paypal page about it.
The solution to this, in .NET 4.5 is
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
If you don’t have .NET 4.5 then use
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
Make sure the ServicePointManager settings are made before the HttpWebRequest is created, else it will not work.
Works:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
Fails:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
Note: Several of the highest voted answers here advise setting ServicePointManager.SecurityProtocol, but Microsoft explicitly advises against doing that. Below, I go into the typical cause of this issue and the best practices for resolving it.
One of the biggest causes of this issue is the active .NET Framework version. The .NET framework runtime version affects which security protocols are enabled by default.
In ASP.NET sites, the framework runtime version is often specified in web.config. (see below)
In other apps, the runtime version is usually the version for which the project was built, regardless of whether it is running on a machine with a newer .NET version.
There doesn't seem to be any authoritative documentation on how it specifically works in different versions, but it seems the defaults are determined more or less as follows:
Framework Version
Default Protocols
4.5 and earlier
SSL 3.0, TLS 1.0
4.6.x
TLS 1.0, 1.1, 1.2, 1.3
4.7+
System (OS) Defaults
For the older versions, your mileage may vary somewhat based on which .NET runtimes are installed on the system. For example, there could be a situation where you are using a very old framework and TLS 1.0 is not supported, or using 4.6.x and TLS 1.3 is not supported.
Microsoft's documentation strongly advises using 4.7+ and the system defaults:
We recommend that you:
Target .NET Framework 4.7 or later versions on your apps. Target .NET Framework 4.7.1 or later versions on your WCF apps.
Do not specify the TLS version. Configure your code to let the OS decide on the TLS version.
Perform a thorough code audit to verify you're not specifying a TLS or SSL version.
For ASP.NET sites: check the targetFramework version in your <httpRuntime> element, as this (when present) determines which runtime is actually used by your site:
<httpRuntime targetFramework="4.5" />
Better:
<httpRuntime targetFramework="4.7" />
I had this problem trying to hit https://ct.mob0.com/Styles/Fun.png, which is an image distributed by CloudFlare on its CDN that supports crazy stuff like SPDY and weird redirect SSL certs.
Instead of specifying Ssl3 as in Simons answer I was able to fix it by going down to Tls12 like this:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
new WebClient().DownloadData("https://ct.mob0.com/Styles/Fun.png");
The problem you're having is that the aspNet user doesn't have access to the certificate. You have to give access using the winhttpcertcfg.exe
An example on how to set this up is at:
http://support.microsoft.com/kb/901183
Under step 2 in more information
EDIT: In more recent versions of IIS, this feature is built in to the certificate manager tool - and can be accessed by right clicking on the certificate and using the option for managing private keys. More details here: https://serverfault.com/questions/131046/how-to-grant-iis-7-5-access-to-a-certificate-in-certificate-store/132791#132791
After many long hours with this same issue I found that the ASP.NET account the client service was running under didn't have access to the certificate. I fixed it by going into the IIS Application Pool that the web app runs under, going into Advanced Settings, and changing the Identity to the LocalSystem account from NetworkService.
A better solution is to get the certificate working with the default NetworkService account but this works for quick functional testing.
The error is generic and there are many reasons why the SSL/TLS negotiation may fail. The most common is an invalid or expired server certificate, and you took care of that by providing your own server certificate validation hook, but is not necessarily the only reason. The server may require mutual authentication, it may be configured with a suites of ciphers not supported by your client, it may have a time drift too big for the handshake to succeed and many more reasons.
The best solution is to use the SChannel troubleshooting tools set. SChannel is the SSPI provider responsible for SSL and TLS and your client will use it for the handshake. Take a look at TLS/SSL Tools and Settings.
Also see How to enable Schannel event logging.
The approach with setting
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Seems to be okay, because Tls1.2 is latest version of secure protocol. But I decided to look deeper and answer do we really need to hardcode it.
Specs: Windows Server 2012R2 x64.
From the internet there is told that .NetFramework 4.6+ must use Tls1.2 by default. But when I updated my project to 4.6 nothing happened.
I have found some info that tells I need manually do some changes to enable Tls1.2 by default
https://support.microsoft.com/en-in/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi
But proposed windows update doesnt work for R2 version
But what helped me is adding 2 values to registry. You can use next PS script so they will be added automatically
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
That is kind of what I was looking for. But still I cant answer on question why NetFramework 4.6+ doesn't set this ...Protocol value automatically?
Another possible cause of the The request was aborted: Could not create SSL/TLS secure channel error is a mismatch between your client PC's configured cipher_suites values, and the values that the server is configured as being willing and able to accept. In this case, when your client sends the list of cipher_suites values that it is able to accept in its initial SSL handshaking/negotiation "Client Hello" message, the server sees that none of the provided values are acceptable, and may return an "Alert" response instead of proceeding to the "Server Hello" step of the SSL handshake.
To investigate this possibility, you can download Microsoft Message Analyzer, and use it to run a trace on the SSL negotiation that occurs when you try and fail to establish an HTTPS connection to the server (in your C# app).
If you are able to make a successful HTTPS connection from another environment (e.g. the Windows XP machine that you mentioned -- or possibly by hitting the HTTPS URL in a non-Microsoft browser that doesn't use the OS's cipher suite settings, such as Chrome or Firefox), run another Message Analyzer trace in that environment to capture what happens when the SSL negotiation succeeds.
Hopefully, you'll see some difference between the two Client Hello messages that will allow you to pinpoint exactly what about the failing SSL negotiation is causing it to fail. Then you should be able to make configuration changes to Windows that will allow it to succeed. IISCrypto is a great tool to use for this (even for client PCs, despite the "IIS" name).
The following two Windows registry keys govern the cipher_suites values that your PC will use:
HKLM\SOFTWARE\Policies\Microsoft\Cryptography\Configuration\SSL\00010002
HKLM\SYSTEM\CurrentControlSet\Control\Cryptography\Configuration\Local\SSL\00010002
Here's a full writeup of how I investigated and solved an instance of this variety of the Could not create SSL/TLS secure channel problem: http://blog.jonschneider.com/2016/08/fix-ssl-handshaking-error-in-windows.html
Something the original answer didn't have. I added some more code to make it bullet proof.
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
The top-voted answer will probably be enough for most people. However, in some circumstances, you could continue getting a "Could not create SSL/TLS secure channel" error even after forcing TLS 1.2. If so, you may want to consult this helpful article for additional troubleshooting steps. To summarize: independent of the TLS/SSL version issue, the client and server must agree on a "cipher suite." During the "handshake" phase of the SSL connection, the client will list its supported cipher-suites for the server to check against its own list. But on some Windows machines, certain common cipher-suites may have been disabled (seemingly due to well-intentioned attempts to limit attack surface), decreasing the possibility of the client & server agreeing on a cipher suite. If they cannot agree, then you may see "fatal alert code 40" in the event viewer and "Could not create SSL/TLS secure channel" in your .NET program.
The aforementioned article explains how to list all of a machine's potentially-supported cipher suites and enable additional cipher suites through the Windows Registry. To help check which cipher suites are enabled on the client, try visiting this diagnostic page in MSIE. (Using System.Net tracing may give more definitive results.) To check which cipher suites are supported by the server, try this online tool (assuming that the server is Internet-accessible). It should go without saying that Registry edits must be done with caution, especially where networking is involved. (Is your machine a remote-hosted VM? If you were to break networking, would the VM be accessible at all?)
In my company's case, we enabled several additional "ECDHE_ECDSA" suites via Registry edit, to fix an immediate problem and guard against future problems. But if you cannot (or will not) edit the Registry, then numerous workarounds (not necessarily pretty) come to mind. For example: your .NET program could delegate its SSL traffic to a separate Python program (which may itself work, for the same reason that Chrome requests may succeed where MSIE requests fail on an affected machine).
This one is working for me in MVC webclient
public string DownloadSite(string RefinedLink)
{
try
{
Uri address = new Uri(RefinedLink);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
using (WebClient webClient = new WebClient())
{
var stream = webClient.OpenRead(address);
using (StreamReader sr = new StreamReader(stream))
{
var page = sr.ReadToEnd();
return page;
}
}
}
catch (Exception e)
{
log.Error("DownloadSite - error Lin = " + RefinedLink, e);
return null;
}
}
"The request was aborted: Could not create SSL/TLS secure channel" exception can occur if the server is returning an HTTP 401 Unauthorized response to the HTTP request.
You can determine if this is happening by turning on trace-level System.Net logging for your client application, as described in this answer.
Once that logging configuration is in place, run the application and reproduce the error, then look in the logging output for a line like this:
System.Net Information: 0 : [9840] Connection#62912200 - Received status line: Version=1.1, StatusCode=401, StatusDescription=Unauthorized.
In my situation, I was failing to set a particular cookie that the server was expecting, leading to the server responding to the request with the 401 error, which in turn led to the "Could not create SSL/TLS secure channel" exception.
Another possibility is improper certificate importation on the box. Make sure to select encircled check box. Initially I didn't do it, so code was either timing out or throwing same exception as private key could not be located.
I had this problem because my web.config had:
<httpRuntime targetFramework="4.5.2" />
and not:
<httpRuntime targetFramework="4.6.1" />
Doing this helped me:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Finally found solution for me.
Try this adding below line before calling https url (for .Net framework 4.5):
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
As you can tell there are plenty of reasons this might happen. Thought I would add the cause I encountered ...
If you set the value of WebRequest.Timeout to 0, this is the exception that is thrown. Below is the code I had... (Except instead of a hard-coded 0 for the timeout value, I had a parameter which was inadvertently set to 0).
WebRequest webRequest = WebRequest.Create(#"https://myservice/path");
webRequest.ContentType = "text/html";
webRequest.Method = "POST";
string body = "...";
byte[] bytes = Encoding.ASCII.GetBytes(body);
webRequest.ContentLength = bytes.Length;
var os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
webRequest.Timeout = 0; //setting the timeout to 0 causes the request to fail
WebResponse webResponse = webRequest.GetResponse(); //Exception thrown here ...
The root of this exception in my case was that at some point in code the following was being called:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
This is really bad. Not only is it instructing .NET to use an insecure protocol, but this impacts every new WebClient (and similar) request made afterward within your appdomain. (Note that incoming web requests are unaffected in your ASP.NET app, but new WebClient requests, such as to talk to an external web service, are).
In my case, it was not actually needed, so I could just delete the statement and all my other web requests started working fine again. Based on my reading elsewhere, I learned a few things:
This is a global setting in your appdomain, and if you have concurrent activity, you can't reliably set it to one value, do your action, and then set it back. Another action may take place during that small window and be impacted.
The correct setting is to leave it default. This allows .NET to continue to use whatever is the most secure default value as time goes on and you upgrade frameworks. Setting it to TLS12 (which is the most secure as of this writing) will work now but in 5 years may start causing mysterious problems.
If you really need to set a value, you should consider doing it in a separate specialized application or appdomain and find a way to talk between it and your main pool. Because it's a single global value, trying to manage it within a busy app pool will only lead to trouble. This answer: https://stackoverflow.com/a/26754917/7656 provides a possible solution by way of a custom proxy. (Note I have not personally implemented it.)
In my case, the service account running the application did not have permission to access the private key. Once I gave this permission, the error went away
mmc
certificates
Expand to personal
select cert
right click
All tasks
Manage private keys
Add the service account user
If you are running your code from Visual Studio, try running Visual Studio as administrator. Fixed the issue for me.
System.Net.WebException: The request was aborted: Could not create
SSL/TLS secure channel.
In our case, we where using a software vendor so we didn't have access to modify the .NET code. Apparently .NET 4 won't use TLS v 1.2 unless there is a change.
The fix for us was adding the SchUseStrongCrypto key to the registry. You can copy/paste the below code into a text file with the .reg extension and execute it. It served as our "patch" to the problem.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
I have struggled with this problem all day.
When I created a new project with .NET 4.5 I finally got it to work.
But if I downgraded to 4.0 I got the same problem again, and it was irreversable for that project (even when i tried to upgrade to 4.5 again).
Strange no other error message but "The request was aborted: Could not create SSL/TLS secure channel." came up for this error
In case that the client is a windows machine, a possible reason could be that the tls or ssl protocol required by the service is not activated.
This can be set in:
Control Panel -> Network and Internet -> Internet Options -> Advanced
Scroll settings down to "Security" and choose between
Use SSL 2.0
Use SSL 3.0
Use TLS 1.0
Use TLS 1.1
Use TLS 1.2
none of this answer not working for me , the google chrome and postman work and handshake the server but ie and .net not working. in google chrome in security tab > connection show that encrypted and authenticated using ECDHE_RSA with P-256 and AES_256_GCM cipher suite to handshake with the server.
i install IIS Crypto and in cipher suites list on windows server 2012 R2 ican't find ECDHE_RSA with P-256 and AES_256_GCM cipher suite. then i update windows to the last version but the problem not solve. finally after searches i understood that windows server 2012 R2 not support GSM correctly and update my server to windows server 2016 and my problem solved.
I was having this same issue and found this answer worked properly for me. The key is 3072. This link provides the details on the '3072' fix.
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
XmlReader r = XmlReader.Create(url);
SyndicationFeed albums = SyndicationFeed.Load(r);
In my case two feeds required the fix:
https://www.fbi.gov/feeds/fbi-in-the-news/atom.xml
https://www.wired.com/feed/category/gear/latest/rss
None of the answers worked for me.
This is what worked:
Instead of initializing my X509Certifiacte2 like this:
var certificate = new X509Certificate2(bytes, pass);
I did it like this:
var certificate = new X509Certificate2(bytes, pass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
Notice the X509KeyStorageFlags.Exportable !!
I didn't change the rest of the code (the WebRequest itself):
// I'm not even sure the first two lines are necessary:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
request = (HttpWebRequest)WebRequest.Create(string.Format("https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", server));
request.Method = "GET";
request.Referer = string.Format("https://hercules.sii.cl/cgi_AUT2000/autInicio.cgi?referencia=https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", servidor);
request.UserAgent = "Mozilla/4.0";
request.ClientCertificates.Add(certificate);
request.CookieContainer = new CookieContainer();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// etc...
}
In fact I'm not even sure that the first two lines are necessary...
Another possibility is that the code being executed doesn't have the required permissions.
In my case, I got this error when using Visual Studio debugger to test a call to a web service. Visual Studio wasn't running as Administrator, which caused this exception.
This fixed for me, add Network Service to permissions.
Right click on the certificate > All Tasks > Manage Private Keys... > Add... > Add "Network Service".

The request was aborted: Could not create SSL/TLS secure channel

We are unable to connect to an HTTPS server using WebRequest because of this error message:
The request was aborted: Could not create SSL/TLS secure channel.
We know that the server doesn't have a valid HTTPS certificate with the path used, but to bypass this issue, we use the following code that we've taken from another StackOverflow post:
private void Somewhere() {
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(AlwaysGoodCertificate);
}
private static bool AlwaysGoodCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
return true;
}
The problem is that server never validates the certificate and fails with the above error. Does anyone have any idea of what I should do?
I should mention that a colleague and I performed tests a few weeks ago and it was working fine with something similar to what I wrote above. The only "major difference" we've found is that I'm using Windows 7 and he was using Windows XP. Does that change something?
I finally found the answer (I haven't noted my source but it was from a search);
While the code works in Windows XP, in Windows 7, you must add this at the beginning:
// using System.Net;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Use SecurityProtocolType.Ssl3 if needed for compatibility reasons
And now, it works perfectly.
ADDENDUM
As mentioned by Robin French; if you are getting this problem while configuring PayPal, please note that they won't support SSL3 starting by December, 3rd 2018. You'll need to use TLS. Here's Paypal page about it.
The solution to this, in .NET 4.5 is
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
If you don’t have .NET 4.5 then use
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
Make sure the ServicePointManager settings are made before the HttpWebRequest is created, else it will not work.
Works:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
Fails:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://google.com/api/")
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12
| SecurityProtocolType.Ssl3;
Note: Several of the highest voted answers here advise setting ServicePointManager.SecurityProtocol, but Microsoft explicitly advises against doing that. Below, I go into the typical cause of this issue and the best practices for resolving it.
One of the biggest causes of this issue is the active .NET Framework version. The .NET framework runtime version affects which security protocols are enabled by default.
In ASP.NET sites, the framework runtime version is often specified in web.config. (see below)
In other apps, the runtime version is usually the version for which the project was built, regardless of whether it is running on a machine with a newer .NET version.
There doesn't seem to be any authoritative documentation on how it specifically works in different versions, but it seems the defaults are determined more or less as follows:
Framework Version
Default Protocols
4.5 and earlier
SSL 3.0, TLS 1.0
4.6.x
TLS 1.0, 1.1, 1.2, 1.3
4.7+
System (OS) Defaults
For the older versions, your mileage may vary somewhat based on which .NET runtimes are installed on the system. For example, there could be a situation where you are using a very old framework and TLS 1.0 is not supported, or using 4.6.x and TLS 1.3 is not supported.
Microsoft's documentation strongly advises using 4.7+ and the system defaults:
We recommend that you:
Target .NET Framework 4.7 or later versions on your apps. Target .NET Framework 4.7.1 or later versions on your WCF apps.
Do not specify the TLS version. Configure your code to let the OS decide on the TLS version.
Perform a thorough code audit to verify you're not specifying a TLS or SSL version.
For ASP.NET sites: check the targetFramework version in your <httpRuntime> element, as this (when present) determines which runtime is actually used by your site:
<httpRuntime targetFramework="4.5" />
Better:
<httpRuntime targetFramework="4.7" />
I had this problem trying to hit https://ct.mob0.com/Styles/Fun.png, which is an image distributed by CloudFlare on its CDN that supports crazy stuff like SPDY and weird redirect SSL certs.
Instead of specifying Ssl3 as in Simons answer I was able to fix it by going down to Tls12 like this:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
new WebClient().DownloadData("https://ct.mob0.com/Styles/Fun.png");
The problem you're having is that the aspNet user doesn't have access to the certificate. You have to give access using the winhttpcertcfg.exe
An example on how to set this up is at:
http://support.microsoft.com/kb/901183
Under step 2 in more information
EDIT: In more recent versions of IIS, this feature is built in to the certificate manager tool - and can be accessed by right clicking on the certificate and using the option for managing private keys. More details here: https://serverfault.com/questions/131046/how-to-grant-iis-7-5-access-to-a-certificate-in-certificate-store/132791#132791
After many long hours with this same issue I found that the ASP.NET account the client service was running under didn't have access to the certificate. I fixed it by going into the IIS Application Pool that the web app runs under, going into Advanced Settings, and changing the Identity to the LocalSystem account from NetworkService.
A better solution is to get the certificate working with the default NetworkService account but this works for quick functional testing.
The error is generic and there are many reasons why the SSL/TLS negotiation may fail. The most common is an invalid or expired server certificate, and you took care of that by providing your own server certificate validation hook, but is not necessarily the only reason. The server may require mutual authentication, it may be configured with a suites of ciphers not supported by your client, it may have a time drift too big for the handshake to succeed and many more reasons.
The best solution is to use the SChannel troubleshooting tools set. SChannel is the SSPI provider responsible for SSL and TLS and your client will use it for the handshake. Take a look at TLS/SSL Tools and Settings.
Also see How to enable Schannel event logging.
The approach with setting
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Seems to be okay, because Tls1.2 is latest version of secure protocol. But I decided to look deeper and answer do we really need to hardcode it.
Specs: Windows Server 2012R2 x64.
From the internet there is told that .NetFramework 4.6+ must use Tls1.2 by default. But when I updated my project to 4.6 nothing happened.
I have found some info that tells I need manually do some changes to enable Tls1.2 by default
https://support.microsoft.com/en-in/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi
But proposed windows update doesnt work for R2 version
But what helped me is adding 2 values to registry. You can use next PS script so they will be added automatically
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
That is kind of what I was looking for. But still I cant answer on question why NetFramework 4.6+ doesn't set this ...Protocol value automatically?
Another possible cause of the The request was aborted: Could not create SSL/TLS secure channel error is a mismatch between your client PC's configured cipher_suites values, and the values that the server is configured as being willing and able to accept. In this case, when your client sends the list of cipher_suites values that it is able to accept in its initial SSL handshaking/negotiation "Client Hello" message, the server sees that none of the provided values are acceptable, and may return an "Alert" response instead of proceeding to the "Server Hello" step of the SSL handshake.
To investigate this possibility, you can download Microsoft Message Analyzer, and use it to run a trace on the SSL negotiation that occurs when you try and fail to establish an HTTPS connection to the server (in your C# app).
If you are able to make a successful HTTPS connection from another environment (e.g. the Windows XP machine that you mentioned -- or possibly by hitting the HTTPS URL in a non-Microsoft browser that doesn't use the OS's cipher suite settings, such as Chrome or Firefox), run another Message Analyzer trace in that environment to capture what happens when the SSL negotiation succeeds.
Hopefully, you'll see some difference between the two Client Hello messages that will allow you to pinpoint exactly what about the failing SSL negotiation is causing it to fail. Then you should be able to make configuration changes to Windows that will allow it to succeed. IISCrypto is a great tool to use for this (even for client PCs, despite the "IIS" name).
The following two Windows registry keys govern the cipher_suites values that your PC will use:
HKLM\SOFTWARE\Policies\Microsoft\Cryptography\Configuration\SSL\00010002
HKLM\SYSTEM\CurrentControlSet\Control\Cryptography\Configuration\Local\SSL\00010002
Here's a full writeup of how I investigated and solved an instance of this variety of the Could not create SSL/TLS secure channel problem: http://blog.jonschneider.com/2016/08/fix-ssl-handshaking-error-in-windows.html
Something the original answer didn't have. I added some more code to make it bullet proof.
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
The top-voted answer will probably be enough for most people. However, in some circumstances, you could continue getting a "Could not create SSL/TLS secure channel" error even after forcing TLS 1.2. If so, you may want to consult this helpful article for additional troubleshooting steps. To summarize: independent of the TLS/SSL version issue, the client and server must agree on a "cipher suite." During the "handshake" phase of the SSL connection, the client will list its supported cipher-suites for the server to check against its own list. But on some Windows machines, certain common cipher-suites may have been disabled (seemingly due to well-intentioned attempts to limit attack surface), decreasing the possibility of the client & server agreeing on a cipher suite. If they cannot agree, then you may see "fatal alert code 40" in the event viewer and "Could not create SSL/TLS secure channel" in your .NET program.
The aforementioned article explains how to list all of a machine's potentially-supported cipher suites and enable additional cipher suites through the Windows Registry. To help check which cipher suites are enabled on the client, try visiting this diagnostic page in MSIE. (Using System.Net tracing may give more definitive results.) To check which cipher suites are supported by the server, try this online tool (assuming that the server is Internet-accessible). It should go without saying that Registry edits must be done with caution, especially where networking is involved. (Is your machine a remote-hosted VM? If you were to break networking, would the VM be accessible at all?)
In my company's case, we enabled several additional "ECDHE_ECDSA" suites via Registry edit, to fix an immediate problem and guard against future problems. But if you cannot (or will not) edit the Registry, then numerous workarounds (not necessarily pretty) come to mind. For example: your .NET program could delegate its SSL traffic to a separate Python program (which may itself work, for the same reason that Chrome requests may succeed where MSIE requests fail on an affected machine).
This one is working for me in MVC webclient
public string DownloadSite(string RefinedLink)
{
try
{
Uri address = new Uri(RefinedLink);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
using (WebClient webClient = new WebClient())
{
var stream = webClient.OpenRead(address);
using (StreamReader sr = new StreamReader(stream))
{
var page = sr.ReadToEnd();
return page;
}
}
}
catch (Exception e)
{
log.Error("DownloadSite - error Lin = " + RefinedLink, e);
return null;
}
}
"The request was aborted: Could not create SSL/TLS secure channel" exception can occur if the server is returning an HTTP 401 Unauthorized response to the HTTP request.
You can determine if this is happening by turning on trace-level System.Net logging for your client application, as described in this answer.
Once that logging configuration is in place, run the application and reproduce the error, then look in the logging output for a line like this:
System.Net Information: 0 : [9840] Connection#62912200 - Received status line: Version=1.1, StatusCode=401, StatusDescription=Unauthorized.
In my situation, I was failing to set a particular cookie that the server was expecting, leading to the server responding to the request with the 401 error, which in turn led to the "Could not create SSL/TLS secure channel" exception.
Another possibility is improper certificate importation on the box. Make sure to select encircled check box. Initially I didn't do it, so code was either timing out or throwing same exception as private key could not be located.
I had this problem because my web.config had:
<httpRuntime targetFramework="4.5.2" />
and not:
<httpRuntime targetFramework="4.6.1" />
Doing this helped me:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Finally found solution for me.
Try this adding below line before calling https url (for .Net framework 4.5):
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
As you can tell there are plenty of reasons this might happen. Thought I would add the cause I encountered ...
If you set the value of WebRequest.Timeout to 0, this is the exception that is thrown. Below is the code I had... (Except instead of a hard-coded 0 for the timeout value, I had a parameter which was inadvertently set to 0).
WebRequest webRequest = WebRequest.Create(#"https://myservice/path");
webRequest.ContentType = "text/html";
webRequest.Method = "POST";
string body = "...";
byte[] bytes = Encoding.ASCII.GetBytes(body);
webRequest.ContentLength = bytes.Length;
var os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
webRequest.Timeout = 0; //setting the timeout to 0 causes the request to fail
WebResponse webResponse = webRequest.GetResponse(); //Exception thrown here ...
The root of this exception in my case was that at some point in code the following was being called:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
This is really bad. Not only is it instructing .NET to use an insecure protocol, but this impacts every new WebClient (and similar) request made afterward within your appdomain. (Note that incoming web requests are unaffected in your ASP.NET app, but new WebClient requests, such as to talk to an external web service, are).
In my case, it was not actually needed, so I could just delete the statement and all my other web requests started working fine again. Based on my reading elsewhere, I learned a few things:
This is a global setting in your appdomain, and if you have concurrent activity, you can't reliably set it to one value, do your action, and then set it back. Another action may take place during that small window and be impacted.
The correct setting is to leave it default. This allows .NET to continue to use whatever is the most secure default value as time goes on and you upgrade frameworks. Setting it to TLS12 (which is the most secure as of this writing) will work now but in 5 years may start causing mysterious problems.
If you really need to set a value, you should consider doing it in a separate specialized application or appdomain and find a way to talk between it and your main pool. Because it's a single global value, trying to manage it within a busy app pool will only lead to trouble. This answer: https://stackoverflow.com/a/26754917/7656 provides a possible solution by way of a custom proxy. (Note I have not personally implemented it.)
In my case, the service account running the application did not have permission to access the private key. Once I gave this permission, the error went away
mmc
certificates
Expand to personal
select cert
right click
All tasks
Manage private keys
Add the service account user
If you are running your code from Visual Studio, try running Visual Studio as administrator. Fixed the issue for me.
System.Net.WebException: The request was aborted: Could not create
SSL/TLS secure channel.
In our case, we where using a software vendor so we didn't have access to modify the .NET code. Apparently .NET 4 won't use TLS v 1.2 unless there is a change.
The fix for us was adding the SchUseStrongCrypto key to the registry. You can copy/paste the below code into a text file with the .reg extension and execute it. It served as our "patch" to the problem.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
I have struggled with this problem all day.
When I created a new project with .NET 4.5 I finally got it to work.
But if I downgraded to 4.0 I got the same problem again, and it was irreversable for that project (even when i tried to upgrade to 4.5 again).
Strange no other error message but "The request was aborted: Could not create SSL/TLS secure channel." came up for this error
In case that the client is a windows machine, a possible reason could be that the tls or ssl protocol required by the service is not activated.
This can be set in:
Control Panel -> Network and Internet -> Internet Options -> Advanced
Scroll settings down to "Security" and choose between
Use SSL 2.0
Use SSL 3.0
Use TLS 1.0
Use TLS 1.1
Use TLS 1.2
none of this answer not working for me , the google chrome and postman work and handshake the server but ie and .net not working. in google chrome in security tab > connection show that encrypted and authenticated using ECDHE_RSA with P-256 and AES_256_GCM cipher suite to handshake with the server.
i install IIS Crypto and in cipher suites list on windows server 2012 R2 ican't find ECDHE_RSA with P-256 and AES_256_GCM cipher suite. then i update windows to the last version but the problem not solve. finally after searches i understood that windows server 2012 R2 not support GSM correctly and update my server to windows server 2016 and my problem solved.
I was having this same issue and found this answer worked properly for me. The key is 3072. This link provides the details on the '3072' fix.
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
XmlReader r = XmlReader.Create(url);
SyndicationFeed albums = SyndicationFeed.Load(r);
In my case two feeds required the fix:
https://www.fbi.gov/feeds/fbi-in-the-news/atom.xml
https://www.wired.com/feed/category/gear/latest/rss
None of the answers worked for me.
This is what worked:
Instead of initializing my X509Certifiacte2 like this:
var certificate = new X509Certificate2(bytes, pass);
I did it like this:
var certificate = new X509Certificate2(bytes, pass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
Notice the X509KeyStorageFlags.Exportable !!
I didn't change the rest of the code (the WebRequest itself):
// I'm not even sure the first two lines are necessary:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
request = (HttpWebRequest)WebRequest.Create(string.Format("https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", server));
request.Method = "GET";
request.Referer = string.Format("https://hercules.sii.cl/cgi_AUT2000/autInicio.cgi?referencia=https://{0}.sii.cl/cvc_cgi/dte/of_solicita_folios", servidor);
request.UserAgent = "Mozilla/4.0";
request.ClientCertificates.Add(certificate);
request.CookieContainer = new CookieContainer();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// etc...
}
In fact I'm not even sure that the first two lines are necessary...
Another possibility is that the code being executed doesn't have the required permissions.
In my case, I got this error when using Visual Studio debugger to test a call to a web service. Visual Studio wasn't running as Administrator, which caused this exception.
This fixed for me, add Network Service to permissions.
Right click on the certificate > All Tasks > Manage Private Keys... > Add... > Add "Network Service".

Categories