Datasource error запрос был прерван не удалось создать защищенный канал ssl tls подробные сведения

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 ...

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.

answered May 25, 2010 at 13:18

Simon Dugré's user avatar

Simon DugréSimon Dugré

17.5k11 gold badges55 silver badges73 bronze badges

24

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;

answered Feb 22, 2018 at 14:46

Andrej Z's user avatar

4

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;

soccer7's user avatar

soccer7

3,2413 gold badges28 silver badges49 bronze badges

answered Jun 21, 2018 at 21:39

hogarth45's user avatar

hogarth45hogarth45

3,2471 gold badge22 silver badges27 bronze badges

8

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" />

answered Oct 2, 2019 at 6:02

JLRishe's user avatar

JLRisheJLRishe

98k19 gold badges130 silver badges166 bronze badges

5

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");

InteXX's user avatar

InteXX

5,8956 gold badges40 silver badges73 bronze badges

answered Oct 15, 2014 at 17:42

Bryan Legend's user avatar

Bryan LegendBryan Legend

6,7221 gold badge59 silver badges60 bronze badges

3

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.

answered Dec 4, 2014 at 16:31

Nick Gotch's user avatar

Nick GotchNick Gotch

9,11914 gold badges70 silver badges95 bronze badges

3

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.

answered May 18, 2010 at 18:14

Remus Rusanu's user avatar

Remus RusanuRemus Rusanu

286k40 gold badges430 silver badges565 bronze badges

3

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:SOFTWAREWow6432NodeMicrosoft.NetFrameworkv4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:SOFTWAREMicrosoft.NetFrameworkv4.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?

answered Oct 28, 2019 at 20:58

simply good's user avatar

simply goodsimply good

9211 gold badge12 silver badges25 bronze badges

5

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:

  • HKLMSOFTWAREPoliciesMicrosoftCryptographyConfigurationSSL0010002
  • HKLMSYSTEMCurrentControlSetControlCryptographyConfigurationLocalSSL0010002

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

answered Aug 31, 2016 at 4:33

Jon Schneider's user avatar

Jon SchneiderJon Schneider

24.9k21 gold badges144 silver badges167 bronze badges

3

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;

answered Jun 1, 2016 at 15:05

SpoiledTechie.com's user avatar

SpoiledTechie.comSpoiledTechie.com

10.4k20 gold badges77 silver badges99 bronze badges

5

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).

answered Jun 1, 2019 at 6:16

APW's user avatar

APWAPW

3544 silver badges6 bronze badges

1

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

soccer7's user avatar

soccer7

3,2413 gold badges28 silver badges49 bronze badges

answered Oct 4, 2017 at 7:14

Arun Prasad E S's user avatar

Arun Prasad E SArun Prasad E S

9,1338 gold badges73 silver badges84 bronze badges

3

«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.

HoldOffHunger's user avatar

answered Aug 19, 2014 at 19:55

Jon Schneider's user avatar

Jon SchneiderJon Schneider

24.9k21 gold badges144 silver badges167 bronze badges

1

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.

certificate importation dialog

answered Jul 11, 2012 at 22:27

Sherlock's user avatar

SherlockSherlock

1,0128 silver badges18 bronze badges

1

I had this problem because my web.config had:

<httpRuntime targetFramework="4.5.2" />

and not:

<httpRuntime targetFramework="4.6.1" />

answered Aug 15, 2017 at 10:47

Terje Solem's user avatar

Terje SolemTerje Solem

7661 gold badge9 silver badges25 bronze badges

1

Doing this helped me:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

answered Jan 26, 2021 at 22:39

Merlyn007's user avatar

Merlyn007Merlyn007

4091 gold badge7 silver badges21 bronze badges

0

Finally found solution for me.

Try this adding below line before calling https url (for .Net framework 4.5):

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Luis Teijon's user avatar

Luis Teijon

4,6737 gold badges35 silver badges56 bronze badges

answered Jun 16, 2021 at 5:24

Priyank Sharma's user avatar

0

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 ...

answered Apr 25, 2014 at 20:50

TCC's user avatar

TCCTCC

2,5061 gold badge23 silver badges35 bronze badges

1

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.)

Community's user avatar

answered Sep 16, 2016 at 23:54

Tyler Forsythe's user avatar

1

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

  1. mmc
  2. certificates
  3. Expand to personal
  4. select cert
  5. right click
  6. All tasks
  7. Manage private keys
  8. Add the service account user

answered Nov 13, 2017 at 21:24

Dinesh Rajan's user avatar

Dinesh RajanDinesh Rajan

2,30823 silver badges17 bronze badges

1

If you are running your code from Visual Studio, try running Visual Studio as administrator. Fixed the issue for me.

answered Feb 27, 2018 at 16:59

handles's user avatar

handleshandles

7,60116 gold badges61 silver badges85 bronze badges

1

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_MACHINESOFTWAREWow6432NodeMicrosoft.NETFrameworkv4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFrameworkv4.0.30319]
"SchUseStrongCrypto"=dword:00000001

answered Jul 26, 2018 at 14:35

capdragon's user avatar

capdragoncapdragon

14.3k24 gold badges102 silver badges152 bronze badges

3

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

answered Dec 2, 2015 at 16:08

aghost's user avatar

aghostaghost

1922 silver badges8 bronze badges

2

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

enter image description here

answered May 10, 2017 at 7:05

cnom's user avatar

cnomcnom

2,8714 gold badges27 silver badges59 bronze badges

4

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.

enter image description here

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.

answered May 31, 2020 at 5:46

sina alizadeh's user avatar

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

Stephen Rauch's user avatar

Stephen Rauch

46.7k31 gold badges109 silver badges131 bronze badges

answered May 27, 2018 at 14:02

joeydood's user avatar

joeydoodjoeydood

511 silver badge4 bronze badges

1

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…

answered Apr 30, 2019 at 17:58

sports's user avatar

sportssports

7,67312 gold badges69 silver badges128 bronze badges

2

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.

answered Oct 30, 2019 at 10:11

OfirD's user avatar

OfirDOfirD

7,9753 gold badges43 silver badges78 bronze badges

This fixed for me, add Network Service to permissions.
Right click on the certificate > All Tasks > Manage Private Keys… > Add… > Add «Network Service».

Lionel Gaillard's user avatar

answered Apr 6, 2018 at 6:27

jayasurya_j's user avatar

jayasurya_jjayasurya_j

1,4191 gold badge13 silver badges22 bronze badges

1

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.

answered May 25, 2010 at 13:18

Simon Dugré's user avatar

Simon DugréSimon Dugré

17.5k11 gold badges55 silver badges73 bronze badges

24

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;

answered Feb 22, 2018 at 14:46

Andrej Z's user avatar

4

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;

soccer7's user avatar

soccer7

3,2413 gold badges28 silver badges49 bronze badges

answered Jun 21, 2018 at 21:39

hogarth45's user avatar

hogarth45hogarth45

3,2471 gold badge22 silver badges27 bronze badges

8

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" />

answered Oct 2, 2019 at 6:02

JLRishe's user avatar

JLRisheJLRishe

98k19 gold badges130 silver badges166 bronze badges

5

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");

InteXX's user avatar

InteXX

5,8956 gold badges40 silver badges73 bronze badges

answered Oct 15, 2014 at 17:42

Bryan Legend's user avatar

Bryan LegendBryan Legend

6,7221 gold badge59 silver badges60 bronze badges

3

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.

answered Dec 4, 2014 at 16:31

Nick Gotch's user avatar

Nick GotchNick Gotch

9,11914 gold badges70 silver badges95 bronze badges

3

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.

answered May 18, 2010 at 18:14

Remus Rusanu's user avatar

Remus RusanuRemus Rusanu

286k40 gold badges430 silver badges565 bronze badges

3

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:SOFTWAREWow6432NodeMicrosoft.NetFrameworkv4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
Set-ItemProperty -Path 'HKLM:SOFTWAREMicrosoft.NetFrameworkv4.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?

answered Oct 28, 2019 at 20:58

simply good's user avatar

simply goodsimply good

9211 gold badge12 silver badges25 bronze badges

5

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:

  • HKLMSOFTWAREPoliciesMicrosoftCryptographyConfigurationSSL0010002
  • HKLMSYSTEMCurrentControlSetControlCryptographyConfigurationLocalSSL0010002

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

answered Aug 31, 2016 at 4:33

Jon Schneider's user avatar

Jon SchneiderJon Schneider

24.9k21 gold badges144 silver badges167 bronze badges

3

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;

answered Jun 1, 2016 at 15:05

SpoiledTechie.com's user avatar

SpoiledTechie.comSpoiledTechie.com

10.4k20 gold badges77 silver badges99 bronze badges

5

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).

answered Jun 1, 2019 at 6:16

APW's user avatar

APWAPW

3544 silver badges6 bronze badges

1

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

soccer7's user avatar

soccer7

3,2413 gold badges28 silver badges49 bronze badges

answered Oct 4, 2017 at 7:14

Arun Prasad E S's user avatar

Arun Prasad E SArun Prasad E S

9,1338 gold badges73 silver badges84 bronze badges

3

«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.

HoldOffHunger's user avatar

answered Aug 19, 2014 at 19:55

Jon Schneider's user avatar

Jon SchneiderJon Schneider

24.9k21 gold badges144 silver badges167 bronze badges

1

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.

certificate importation dialog

answered Jul 11, 2012 at 22:27

Sherlock's user avatar

SherlockSherlock

1,0128 silver badges18 bronze badges

1

I had this problem because my web.config had:

<httpRuntime targetFramework="4.5.2" />

and not:

<httpRuntime targetFramework="4.6.1" />

answered Aug 15, 2017 at 10:47

Terje Solem's user avatar

Terje SolemTerje Solem

7661 gold badge9 silver badges25 bronze badges

1

Doing this helped me:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

answered Jan 26, 2021 at 22:39

Merlyn007's user avatar

Merlyn007Merlyn007

4091 gold badge7 silver badges21 bronze badges

0

Finally found solution for me.

Try this adding below line before calling https url (for .Net framework 4.5):

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Luis Teijon's user avatar

Luis Teijon

4,6737 gold badges35 silver badges56 bronze badges

answered Jun 16, 2021 at 5:24

Priyank Sharma's user avatar

0

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 ...

answered Apr 25, 2014 at 20:50

TCC's user avatar

TCCTCC

2,5061 gold badge23 silver badges35 bronze badges

1

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.)

Community's user avatar

answered Sep 16, 2016 at 23:54

Tyler Forsythe's user avatar

1

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

  1. mmc
  2. certificates
  3. Expand to personal
  4. select cert
  5. right click
  6. All tasks
  7. Manage private keys
  8. Add the service account user

answered Nov 13, 2017 at 21:24

Dinesh Rajan's user avatar

Dinesh RajanDinesh Rajan

2,30823 silver badges17 bronze badges

1

If you are running your code from Visual Studio, try running Visual Studio as administrator. Fixed the issue for me.

answered Feb 27, 2018 at 16:59

handles's user avatar

handleshandles

7,60116 gold badges61 silver badges85 bronze badges

1

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_MACHINESOFTWAREWow6432NodeMicrosoft.NETFrameworkv4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINESOFTWAREMicrosoft.NETFrameworkv4.0.30319]
"SchUseStrongCrypto"=dword:00000001

answered Jul 26, 2018 at 14:35

capdragon's user avatar

capdragoncapdragon

14.3k24 gold badges102 silver badges152 bronze badges

3

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

answered Dec 2, 2015 at 16:08

aghost's user avatar

aghostaghost

1922 silver badges8 bronze badges

2

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

enter image description here

answered May 10, 2017 at 7:05

cnom's user avatar

cnomcnom

2,8714 gold badges27 silver badges59 bronze badges

4

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.

enter image description here

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.

answered May 31, 2020 at 5:46

sina alizadeh's user avatar

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

Stephen Rauch's user avatar

Stephen Rauch

46.7k31 gold badges109 silver badges131 bronze badges

answered May 27, 2018 at 14:02

joeydood's user avatar

joeydoodjoeydood

511 silver badge4 bronze badges

1

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…

answered Apr 30, 2019 at 17:58

sports's user avatar

sportssports

7,67312 gold badges69 silver badges128 bronze badges

2

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.

answered Oct 30, 2019 at 10:11

OfirD's user avatar

OfirDOfirD

7,9753 gold badges43 silver badges78 bronze badges

This fixed for me, add Network Service to permissions.
Right click on the certificate > All Tasks > Manage Private Keys… > Add… > Add «Network Service».

Lionel Gaillard's user avatar

answered Apr 6, 2018 at 6:27

jayasurya_j's user avatar

jayasurya_jjayasurya_j

1,4191 gold badge13 silver badges22 bronze badges

1

 

Когда хочу создать запрос Power Query — выдает следующую ошибку:
«DataSource.Error: Запрос был прерван: Не удалось создать защищенный канал SSL/TLS»
При том, если беру документы с уже созданным и рабочим запросом, то ошибки не вылетает. Т.е. смотреть запросы могу, а создавать — нет.
Подскажите, что делать, кто знает.

 

Андрей VG

Пользователь

Сообщений: 11878
Регистрация: 22.12.2012

Excel 2016, 365

 

Ranker Dark

Пользователь

Сообщений: 99
Регистрация: 31.03.2020

#3

25.09.2020 23:09:07

Цитата
Андрей VG написал:
Необъявленный кросс.

? И к чему это?

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

К тому, что правила форумов нужно читать и самостоятельно показывать ссылки

 

Юрий М

Модератор

Сообщений: 60383
Регистрация: 14.09.2012

Контакты см. в профиле

#5

25.09.2020 23:11:31

Цитата
Ranker Dark написал:
И к чему это?

Это к тому, что Вы сами должны информировать прямыми ссылками, где ещё разместили свой вопрос.

 

JeyCi

Пользователь

Сообщений: 3351
Регистрация: 27.11.2013

#6

12.06.2021 14:59:15

Цитата
It was because Excel/PowerQuery was using TLS1.0 and the data source server was only using TLS1.2.

Power Query — Could not create SSL/TLS secure channel

— не знаю, поможет ли… на сайты с протоколом TLS1.2 пропускает…
но на сайт с протоколом TLS 1.3 так и не начал пускать…

Изменено: JeyCi13.06.2021 20:35:31

чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

 

JeyCi

Пользователь

Сообщений: 3351
Регистрация: 27.11.2013

How to enable TLS 1.3 support in Firefox and Chrome

— прошлась по линкам — проверила на всякий случай

MyClient

— клиент от chrome то нормальный (поддерживает и TLS1.2 и TLS1.3), но Office 2016 не берёт данные с сайта шифрующегося по протоколу TLS1.3 :(

P.S,
в общем дурная к меня какая-то Windows 10 Корпоративная v1607 —  

по скрину с msdn

у меня в regedit должен быть TLS 1.0 client , а у меня там только SSL 2.0 Client … хотя, как уже отметила выше — сайт грузится в chrome и даже ie, но в PQ не берётся…
обновить NET.Framework тоже не даёт — пишет, что установлена последняя версия, aka 4.8,
при этом почему-то в реестре в LOCAL_MACHINE/SOFTWARE/Microsoft/NET.Framework есть только версии до 4.0 включительно…
странно как-то…
если кто-то знает почему — черканите please ??

Изменено: vikttur13.06.2021 22:45:36

чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

 

JeyCi

Пользователь

Сообщений: 3351
Регистрация: 27.11.2013

#8

13.06.2021 22:26:13

Цитата
JeyCi написал:
у меня там только SSL 2.0 Client

т.е здесь
HKLM SYSTEMCurrentControlSetControlSecurityProvidersSCHANNEL­ProtocolsSSL 2.0Client
а, наверно,

должен быть

Цитата
For example, here are some valid registry paths with version-specific subkeys:
HKLM SYSTEMCurrentControlSetControlSecurityProvidersSCHANNEL­ProtocolsSSL 3.0Client
HKLM SYSTEMCurrentControlSetControlSecurityProvidersSCHANNEL­ProtocolsTLS 1.2Server
HKLM SYSTEMCurrentControlSetControlSecurityProvidersSCHANNEL­ProtocolsDTLS 1.2Client

???
но TLS нет вообще
и не уверена, что дело в этом, т.к.

Цитата
Please note that these registry settings only apply to Schannel SSP

manual создание их не даёт результата

Изменено: vikttur13.06.2021 22:44:32

чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

 

JeyCi

Пользователь

Сообщений: 3351
Регистрация: 27.11.2013

#9

14.06.2021 07:29:52

Цитата
JeyCi написал:
на сайт с протоколом TLS 1.3 так и не начал пускать…

:) дело было не в этом — прописала все заголовки на всякий случай:

Код
let
    Source = Web.Page(Web.Contents("https://www.cmegroup.com", [Headers=[UserAgent="Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101", Accept="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", AcceptEncoding="gzip, deflate, br", #"Accept-Language"="ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7"]])),
    Data0 = Source{0}[Data],
    #"Changed Type" = Table.TransformColumnTypes(Data0,{{"Column1", type text}, {"Column2", type text}})
in
    #"Changed Type"

важно, чтобы user-agent пропускал на сайт с протоколом TLS 1.3 … — нормальный агент нормально берёт TLS 1.3 (посмотрела в Fiddler и по линку из #7)
P.S.
а у меня просто запрос был не прямо на этот сайт, а на json с него… :( продолжаю препарировать

Изменено: JeyCi14.06.2021 07:38:19

чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

 

JeyCi

Пользователь

Сообщений: 3351
Регистрация: 27.11.2013

#10

14.06.2021 21:08:19

Цитата
JeyCi написал:
а у меня просто запрос был не прямо на этот сайт, а на json с него…  продолжаю препарировать

ууууупс

— всё самое значимое всегда пишут мелким шрифтом…

Цитата
1 Available in dataflows for Microsoft Teams.

— json в Power Apps (Dataflows)  8-0
— кажись, это и есть ответ на мой вопрос — уж очень сильно похоже

Изменено: JeyCi14.06.2021 21:11:44

чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

128

Поизучали возможность обновления этих пакетов

Но, похоже, тут только возможность упорядочивания их, но новый пакет в ОС добавить вручную нельзя.

вроде бы неудача.
но, в форумах часто проскальзывает что «хром работает, а .NET Framework приложения — нет». Причина в том, что баузер хром использует свои пакеты шифрования а не полагается ОС.
Мы зацепились за эту идею.

В одном из проектов мы использовали компонент — внедренный браузер на Chromium

пакет в Nuget: CefSharp.Winforms, CefSharp.Common.

Попробовали загрузить страницу через этот механизм — работает!

Решения

то есть у вас есть 2 варианта решения

1. переход на свежий Windows Server 2016

2. использование пакета CefSharp но предупреждаю, он увеличивает размер приложения (в нашем случае на 100+ МБ)

Если нужны будут детальные инструкции по CefSharp -напишите в комментах: сделаю отдельную статью.

Источник

Запрос был прерван: не удалось создать безопасный канал SSL/TLS

Мы не можем подключиться к серверу HTTPS с помощью WebRequest из-за этого сообщения об ошибке:

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

Мы знаем, что сервер не имеет действительного сертификата HTTPS с указанным путем, но чтобы обойти эту проблему, мы используем следующий код, который мы взяли из другого сообщения StackOverflow:

Проблема в том, что сервер никогда не проверяет сертификат и не выполняет вышеуказанную ошибку. Кто-нибудь знает, что мне делать?

Я должен упомянуть, что несколько лет назад мы с коллегой проводили тесты, и он отлично работал с чем-то похожим на то, что я написал выше. Единственное “основное отличие”, которое мы обнаружили, это то, что я использую Windows 7, и он использовал Windows XP. Это что-то меняет?

Я, наконец, нашел ответ (я не заметил свой источник, но это был поиск);

Хотя код работает в Windows XP, в Windows 7, вы должны добавить это в начале:

И теперь он работает отлично.

ДОПОЛНЕНИЕ

Как упоминал Робин Франс; если вы получаете эту проблему при настройке PayPal, обратите внимание, что они не будут поддерживать SSL3, начиная с 3 декабря 2018 года. Вам нужно будет использовать TLS. Здесь страница Paypal об этом.

Решение этого в.NET 4.5 является

Если у вас нет.NET 4.5, используйте

Убедитесь, что настройки ServicePointManager заданы до создания HttpWebRequest, иначе он не будет работать.

Проблема, с которой вы сталкиваетесь, заключается в том, что пользователь aspNet не имеет доступа к сертификату. Вы должны предоставить доступ, используя winhttpcertcfg.exe

На шаге 2 в дополнительной информации

EDIT: в более поздних версиях IIS эта функция встроена в инструмент диспетчера сертификатов – и к ней можно получить доступ, щелкнув правой кнопкой мыши по сертификату и используя опцию для управления секретными ключами. Подробнее здесь: https://serverfault.com/questions/131046/how-to-grant-iis-7-5-access-to-a-certificate-in-certificate-store/132791#132791

Ошибка является общей и существует много причин, по которым переговоры SSL/TLS могут завершиться неудачей. Наиболее распространенным является недействительный или устаревший сертификат сервера, и вы позаботились об этом, предоставив свой собственный сертификат проверки подлинности сертификата сервера, но это не обязательно единственная причина. Сервер может требовать взаимной аутентификации, он может быть настроен с наборами шифров, не поддерживаемых вашим клиентом, у него может быть слишком большой дрейф времени, чтобы рукопожатие преуспело и еще много причин.

Лучшим решением является использование набора инструментов устранения неполадок SChannel. SChannel – поставщик SSPI, ответственный за SSL и TLS, и ваш клиент будет использовать его для рукопожатия. Посмотрите TLS/SSL-инструменты и настройки.

У меня была эта проблема с попыткой нажать https://ct.mob0.com/Styles/Fun.png, который представляет собой изображение, распространяемое CloudFlare на нем CDN, которое поддерживает сумасшедшие вещи, такие как SPDY и странные перенаправления сертификатов SSL.

Вместо того, чтобы указывать Ssl3, как в ответе Саймонса, я смог исправить его, перейдя к Tls12 следующим образом:

После долгих часов с этой же проблемой я обнаружил, что учетная запись ASP.NET, на которой работает клиентская служба, не имела доступа к сертификату. Я исправил его, перейдя в пул приложений IIS, с которым работает веб-приложение, перейдя в “Дополнительные настройки” и изменив идентификатор на LocalSystem с NetworkService .

Лучшим решением является получение сертификата, работающего с учетной записью по умолчанию NetworkService , но это работает для быстрого функционального тестирования.

Что-то, чего не было в первоначальном ответе. Я добавил еще один код, чтобы сделать его пуленепробиваемым.

Другая возможность – это неправильный импорт сертификата в поле. Обязательно установите флажок в окружении. Первоначально я этого не делал, поэтому код либо выходил из строя, либо выдавал такое же исключение, что и закрытый ключ.

“Запрос был прерван: не удалось создать безопасный канал SSL/TLS”. Исключение может возникнуть, если сервер возвращает ответ HTTP Неавторизованный запрос HTTP.

Вы можете определить, происходит ли это, включив ведение журнала System.Net на уровне трассировки для вашего клиентского приложения, как описано в этом ответе.

Как только эта конфигурация регистрации будет на месте, запустите приложение и воспроизведите ошибку, а затем посмотрите в выводе журнала для такой строки:

В моей ситуации я не смог установить конкретный файл cookie, ожидаемый сервером, что привело к тому, что сервер ответил на запрос с ошибкой 401, что в свою очередь привело к созданию “Не удалось создать безопасный канал SSL/TLS”, исключение.

Корень этого исключения в моем случае состоял в том, что в какой-то момент кода вызывалось следующее:

Это действительно плохо. Он не только инструктирует .NET использовать небезопасный протокол, но это влияет на каждый новый запрос WebClient (и аналогичный), сделанный впоследствии в вашем приложении. (Обратите внимание, что входящие веб-запросы не затрагиваются в вашем приложении ASP.NET, но новые запросы WebClient, например, для общения с внешней веб-службой).

В моем случае это было фактически не нужно, поэтому я мог просто удалить инструкцию, и все мои другие веб-запросы снова начали работать отлично. Основываясь на моем чтении в другом месте, я узнал несколько вещей:

  • Это глобальная настройка в вашем приложении, и если у вас есть одновременная деятельность, вы не можете надежно установить ее на одно значение, выполнить свое действие и затем установить его обратно. Другое действие может иметь место во время этого маленького окна и быть затронутым.
  • Правильная настройка – оставить ее по умолчанию. Это позволяет .NET продолжать использовать все, что является самым безопасным значением по умолчанию, с течением времени и обновлять фреймворки. Установка его в TLS12 (который является самым безопасным на момент написания этой статьи) будет работать сейчас, но через 5 лет может возникнуть таинственные проблемы.
  • Если вам действительно нужно установить значение, вы должны подумать об этом в отдельном специализированном приложении или приложении домена и найти способ поговорить между ним и вашим основным пулом. Поскольку это единственное глобальное значение, попытка управлять им в пределах загруженного пула приложений приведет только к неприятностям. Этот ответ: qaru.site/questions/45920/… предоставляет возможное решение с помощью специального прокси. (Примечание. Я лично не реализовал его.)

Как вы можете сказать, есть много причин, которые могут произойти. Думаю, я бы добавил причину, с которой я столкнулся…

Если вы установите значение WebRequest.Timeout на 0 , это будет исключение. Ниже приведен код, который у меня был… (За исключением жестко закодированного 0 для значения таймаута у меня был параметр, который был непреднамеренно установлен на 0 ).

Этот работает для меня в веб-клиенте MVC

Другая возможная причина The request was aborted: Could not create SSL/TLS secure channel ошибку The request was aborted: Could not create SSL/TLS secure channel – это несоответствие между вашими значениями cipher_suites вашего клиентского ПК и значениями, которые сервер настроил как желающий и способный принять. В этом случае, когда ваш клиент отправляет список значений cipher_suites, которые он может принять в своем первоначальном сообщении об установлении связи/согласовании SSL “Клиент Hello”, сервер видит, что ни одно из предоставленных значений не является приемлемым и может возвращать “Предупреждение” “вместо того, чтобы перейти к шагу” Приветствие Сервера “SSL-квитирования.

Чтобы изучить эту возможность, вы можете загрузить Microsoft Message Analyzer и использовать его для запуска трассировки в согласовании SSL, возникающего при попытке установить HTTPS-соединение с сервером (в вашем приложении С#).

Если вы можете сделать успешное соединение HTTPS из другой среды (например, упомянутой вами машины Windows XP, или, возможно, нажав URL-адрес HTTPS в браузере, отличном от Microsoft, который не использует настройки набора шифров ОС, например Chrome или Firefox), запустите еще одну трассировку анализатора сообщений в этой среде, чтобы зафиксировать, что происходит, когда переговоры по SSL успешно завершены.

Надеемся, вы увидите некоторую разницу между двумя сообщениями Hello Hello, которые позволят вам точно определить, что из-за неудачного согласования SSL приводит к сбою. Затем вы сможете внести изменения в конфигурацию Windows, что позволит ей добиться успеха. IISCrypto – отличный инструмент для этого (даже для клиентских компьютеров, несмотря на имя “IIS”).

Следующие два ключа реестра Windows управляют значениями cipher_suites, которые ваш компьютер будет использовать:

Здесь полная запись того, как я исследовал и решил экземпляр этого многообразия. Could not create SSL/TLS secure channel проблему Could not create SSL/TLS secure channel : http://blog.jonschneider.com/2016/08/fix-ssl-handshaking-error-in -windows.html

У меня была эта проблема, потому что у моего web.config было:

Я боролся с этой проблемой весь день.

Когда я создал новый проект с .NET 4.5, я, наконец, получил его для работы.

Но если я понизил до 4.0, я снова получил ту же проблему, и это было необратимо для этого проекта (даже когда я снова попытался обновить до 4.5).

Странное другое сообщение об ошибке, но “Запрос был прерван: не удалось создать безопасный канал SSL/TLS”. придумал эту ошибку

В случае, если клиент является машиной Windows, возможной причиной может быть то, что протокол tls или ssl, требуемый службой, не активирован.

Это можно установить в:

Панель управления → Сеть и Интернет → Свойства обозревателя → Дополнительно

Прокрутите настройки до “Безопасность” и выберите между

  • Использовать SSL 2.0
  • Использовать SSL 3.0
  • Использовать TLS 1.0
  • Использовать TLS 1.1
  • Использовать TLS 1.2

В моем случае учетная запись службы, запускающая приложение, не имела права доступа к закрытому ключу. Как только я дал это разрешение, ошибка исчезла.

  • ММС
  • сертификаты
  • Развернуть до личного
  • выберите cert
  • щелкните правой кнопкой мыши
  • Все задачи
  • Управление секретными ключами
  • Добавить

Если вы запускаете свой код из Visual Studio, попробуйте запустить Visual Studio в качестве администратора. Исправлена ошибка.

У меня была такая же проблема, и я нашел, что этот ответ работал правильно для меня. Ключ – 3072. Эта ссылка содержит сведения об исправлении 3072.

В моем случае два канала потребовали исправления:

System.Net.WebException: запрос был прерван: не удалось создать безопасный канал SSL/TLS.

В нашем случае мы используем поставщика программного обеспечения, поэтому у нас не было доступа для изменения кода.NET. По-видимому,.NET 4 не будет использовать TLS v 1.2, если не будет изменений.

Исправление для нас заключалось в добавлении ключа SchUseStrongCrypto в реестр. Вы можете скопировать/вставить приведенный ниже код в текстовый файл с расширением.reg и выполнить его. Это послужило нашим “патчем” к проблеме.

Ответа с наибольшим количеством голосов, вероятно, будет достаточно для большинства людей. Однако в некоторых случаях вы можете продолжить получать сообщение об ошибке “Не удалось создать безопасный канал SSL/TLS” даже после принудительного использования TLS 1.2. Если это так, вы можете обратиться к этой полезной статье за дополнительными шагами по устранению неполадок. Подводя итог: независимо от проблемы версии TLS/SSL, клиент и сервер должны договориться о “наборе шифров”. На этапе “рукопожатия” SSL-соединения клиент перечислит свои поддерживаемые комплекты шифров, которые сервер будет проверять по собственному списку. Но на некоторых компьютерах с Windows некоторые общие наборы шифров могут быть отключены (по-видимому, из-за благих намерений попыток ограничить поверхность атаки), уменьшая вероятность клиента & согласие сервера на набор шифров. Если они не могут согласиться, вы можете увидеть “код фатального оповещения 40” в средстве просмотра событий и “Не удалось создать безопасный канал SSL/TLS” в вашей .NET-программе.

В вышеупомянутой статье объясняется, как составить список всех потенциально поддерживаемых наборов шифров на компьютере и включить дополнительные наборы шифров через реестр Windows. Чтобы проверить, какие наборы шифров включены на клиенте, попробуйте посетить эту страницу диагностики в MSIE. (Использование трассировки System.Net может дать более точные результаты.) Чтобы проверить, какие наборы шифров поддерживаются сервером, попробуйте этот онлайн-инструмент (при условии, что сервер доступен через Интернет). Само собой разумеется, что изменения в реестре должны выполняться с осторожностью, особенно когда речь идет о работе в сети. (Является ли ваша машина виртуальной машиной с удаленным размещением? Если бы вы прервали работу сети, была бы она вообще доступна?)

В случае моей компании мы включили несколько дополнительных наборов “ECDHE_ECDSA” через редактирование реестра, чтобы исправить непосредственную проблему и защититься от будущих проблем. Но если вы не можете (или не хотите) редактировать реестр, то на ум приходят многочисленные обходные пути (не обязательно красивые). Например: ваша .NET-программа может делегировать свой SSL-трафик отдельной программе Python (которая может сама работать, по той же причине, по которой запросы Chrome могут выполняться успешно, когда запросы MSIE не выполняются на зараженной машине).

Проблема для меня заключалась в том, что я пытался развернуть IIS в качестве веб-службы, я установил сертификат на сервере, но у пользователя, который запускает IIS, не было правильных разрешений на сертификат.

В моем случае у меня была эта проблема, когда служба Windows пыталась подключиться к веб-службе. В результате в Windows я обнаружил код ошибки.

Идентификатор события 36888 (Schannel) поднят:

Наконец, это связано с исправлением Windows. В моем случае: KB3172605 и KB3177186

Предлагаемое решение в форуме vmware – это добавить запись в Windows. После добавления следующего реестра все работает нормально.

“ClientMinKeyBitLength” = DWORD: 00000200

По-видимому, это связано с отсутствующим значением в рукопожатии https на стороне клиента.

Список Windows HotFix:

Надеюсь, что это поможет.

На этот вопрос может быть много ответов, поскольку он касается общего сообщения об ошибке. Мы столкнулись с этой проблемой на некоторых наших серверах, но не на наших машинах для разработки. После удаления большинства наших волос мы обнаружили, что это ошибка Microsoft.

По сути, MS предполагает, что вам нужно более слабое шифрование, но ОС исправлена только для разрешения TLS 1.2, поэтому вы получаете страшное сообщение “Запрос был прерван: не удалось создать безопасный канал SSL/TLS”.

Есть три исправления.

2) Добавьте настройку в файл app.config/web.config.

3) Добавьте параметр реестра, который уже упоминался в другом ответе.

Все они упомянуты в статье базы знаний, которую я разместил.

Ни один из ответов не сработал для меня.

Вот что сработало:

Вместо инициализации моего X509Certifiacte2 вот так:

Я сделал это так:

Обратите внимание на X509KeyStorageFlags.Exportable !!

Я не изменил остальную часть кода (сам WebRequest ):

На самом деле я даже не уверен, что первые две строки необходимы…

Вы можете попробовать установить демонстрационный сертификат (некоторые провайдеры ssl предлагают их бесплатно в течение месяца), чтобы убедиться, что проблема связана с действительностью сертификата или нет.

Пока это относительно “живая” ссылка, я думал, что добавлю новый вариант. Эта возможность заключается в том, что служба больше не поддерживает SSL 3.0 из-за проблемы с атакой пуделя. Ознакомьтесь с инструкцией Google по этому вопросу. Я столкнулся с этой проблемой сразу с несколькими веб-службами и понял, что что-то должно было произойти. Я переключился на TLS 1.2, и все снова работает.

Это происходило для меня только на одном сайте, и оказалось, что он имел только доступный шифр RC4. При попытке упростить работу с сервером я отключил шифр RC4, как только я снова включил эту проблему, проблема была решена.

Источник

Adblock
detector

Exchange Online Exchange Server 2013 Enterprise Exchange Server 2013 Standard Edition Еще…Меньше

ПРОБЛЕМА

Требуется настройка гибридного развертывания между на предприятии организации Microsoft Exchange Server и Microsoft Exchange Online в Microsoft Office 365. Тем не менее, при запуске мастера настройки гибридного, мастер не запускается и появляется «запрос был прерван: не удалось создать защищенный канал SSL/TLS» сообщение об ошибке. Полный текст сообщения следующего вида:

Ошибка: обновление гибридные конфигурации произошла ошибка «Ошибка выполнения подзадачи настройки: Создание организационных связей.
При выполнении командлета Set-FederatedOrganizationIdentifier исключение. Это может означать недопустимые параметры в параметрах конфигурации гибридных.
Произошла ошибка при попытке подготовки Exchange для STS партнера. Подробные сведения: «произошла ошибка доступа к Windows Live.» Подробная информация: «»запрос был прерван: не удалось создать защищенный канал SSL/TLS.»».»».
в Microsoft.Exchange.Management.Hybrid.RemotePowershellSession.RunCommand (строка командлета, словарь «2 параметров, логическое ignoreNotFoundErrors)

ПРИЧИНА

Эта проблема может возникнуть, если неправильно настроены параметры прокси-сервера или параметры брандмауэра.

РЕШЕНИЕ

  1. Настройте параметры прокси-сервера, чтобы разрешить доступ для конечных точек, используемых службой. Список IP-адресов и URL-адреса, используемые Exchange Online обратитесь к разделу Exchange OnlineOffice 365 URL-адресаи IP-адресов.

  2. Убедитесь, что параметры прокси-сервера настроены правильно на серверах в вашей среде Exchange следующим образом:

    1. Задайте прокси в Internet Explorer. Дополнительные сведения содержатся в разделе Изменение параметров прокси-сервера в обозревателе Internet Explorer.

    2. Задайте прокси с помощью средства командной строки netsh . Дополнительные сведения см в протокол HTTP.

    3. Задайте прокси с помощью командлета Set-ExchangeServer . Например выполните следующую команду:

      Set-ExchangeServer NameOfServer -InternetWebProxy Http://proxyURL:Port 

      Дополнительные сведения содержатся в разделе Set-ExchangeServer.

  3. Вновь запустите мастер настройки гибридного.

Если проблема будет повторяться, обратитесь в Службу технической поддержки Майкрософти ссылки на эту статью базы знаний.

Дополнительные сведения

Если возникают проблемы с помощью мастера настройки гибридного можно запустить Exchange гибридные конфигурации диагностики. Эта диагностика является автоматические функции устранения неполадок. Запустите его на том же сервере, на котором сбой мастера конфигурации гибридных. При этом собирает журналы мастер конфигурации гибридных и анализирует их для вас. Возникают ли проблемы, отображается сообщение о том, что пошло не так. Сообщение содержит ссылку на статью, содержащую решения. В настоящее время диагностики поддерживается только в Internet Explorer.

По-прежнему нужна помощь? Переход на форумах TechNet Exchangeили Сообщества Майкрософт .

Нужна дополнительная помощь?

Оглавление

  • Проблема
  • Windows 7 и Windows 2008 R2
  • Windows RT 8.1, Windows 8.1, Windows Server 2012 R2
  • Другая ОС
  • Проблема с корневыми сертификатами в ОС

Проблема

Ошибка ‘Запрос был прерван: Не удалось создать защищенный канал SSL/TLS’ или что то же самое ‘The request was aborted: Could not create SSL/TLS secure channel’ может возникнуть в обновляторе при операциях скачивания, например, исправлений (патчей) к конфигурациям с сайта 1С.

Если эта ошибка возникает изредка и не влияет на общий ход операции (так как обновлятор делает 3 попытки с паузой при неудачном скачивании), то делать с этим ничего не нужно. Тут причина скорее во временных сбоях при работе сети или самого сервиса 1С.

Но если обновлятор вообще не может ничего скачивать и постоянно при попытках выдаёт эту ошибку, то дело в том, что у вас в операционной системе не установлены необходимые обновления для того, чтобы мог корректно функционировать  протокол TLS.

Он требуется обновлятору при подключении, например, к сервисам 1С. А так как обновлятор написан на .Net Framework, то он опирается во многих своих возможностях на библиотеки операционной системы (в случае c TLS речь идёт о библиотеке schannel.dll).

Windows 7 и Windows 2008 R2

1. Для этих ОС, прежде всего, вам нужно установить Service Pack 1, если он у вас ещё не установлен.

2. Далее нужно установить KB3140245.

3. После этого KB3020369.

4. И, наконец, KB3172605.

5. После этого перезагрузите сервер, чтобы изменения вступили в силу.

Windows RT 8.1, Windows 8.1, Windows Server 2012 R2

1. Для этих ОС нужно установить KB2919355

2. После этого перезагрузите сервер, чтобы изменения вступили в силу.

Другая ОС

Если вы столкнулись с этой ошибкой на ОС, отличной от описанных выше, пожалуйста напишите мне на helpme1c.box@gmail.com и я постараюсь совместно с вами подготовить такую же подробную инструкцию по точечной установке только необходимых обновлений для вашей ОС.

Проблема с корневыми сертификатами в ОС

Ошибка с созданием защищенного канала может быть также связана с тем, что в ОС не обновлены корневые сертификаты.

Подробнее об этом здесь: ссылка.

Как помочь сайту: расскажите (кнопки поделиться ниже) о нём своим друзьям и коллегам. Сделайте это один раз и вы внесете существенный вклад в развитие сайта. На сайте нет рекламы, но чем больше людей им пользуются, тем больше сил у меня для его поддержки.

I found the type of certificate also comes into play.

I had a cert that was:

(the below output was in mmc , certificate properties )

Digital Signature, Key Encipherment (a0)

(the below output was from my C# code below)

X509Extension.X509KeyUsageExtension.KeyUsages=’KeyEncipherment, DigitalSignature’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.CrlSign=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DataEncipherment=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DecipherOnly=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DigitalSignature=’True
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.EncipherOnly=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyAgreement=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyCertSign=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyEncipherment=’True
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.None=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.NonRepudiation=’False’

the above did not work.

===============================

Then another certificate with :

(the below output was in mmc , certificate properties )

Certificate Signing, Off-line CRL Signing, CRL Signing (06)

(the below output was from my C# code below)

X509Extension.X509KeyUsageExtension.KeyUsages=’CrlSign, KeyCertSign’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.CrlSign=’True
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DataEncipherment=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DecipherOnly=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DigitalSignature=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.EncipherOnly=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyAgreement=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyCertSign=’True
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyEncipherment=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.None=’False’
X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.NonRepudiation=’False’

and it did work

The below code will allow you to inspect your client certificate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace MyNamespace
{
    public static class SecurityShower
    {
        public static void ShowHttpWebRequest(System.Net.HttpWebRequest hwr)
        {
            StringBuilder sb = new StringBuilder();
            if (null != hwr)
            {
                sb.Append("-----------------------------------------------HttpWebRequest" + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.Address.AbsolutePath='{0}'", hwr.Address.AbsolutePath) + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.Address.AbsoluteUri='{0}'", hwr.Address.AbsoluteUri) + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.Address='{0}'", hwr.Address) + System.Environment.NewLine);

                sb.Append(string.Format("HttpWebRequest.RequestUri.AbsolutePath='{0}'", hwr.RequestUri.AbsolutePath) + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.RequestUri.AbsoluteUri='{0}'", hwr.RequestUri.AbsoluteUri) + System.Environment.NewLine);
                sb.Append(string.Format("HttpWebRequest.RequestUri='{0}'", hwr.RequestUri) + System.Environment.NewLine);

                foreach (X509Certificate cert in hwr.ClientCertificates)
                {
                    sb.Append("START*************************************************");
                    ShowX509Certificate(sb, cert);
                    sb.Append("END*************************************************");
                }
            }

            string result = sb.ToString();
            Console.WriteLine(result);
        }

        public static void ShowCertAndChain(X509Certificate2 cert)
        {
            X509Chain chain = new X509Chain();
            chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
            chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
            chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags;

            ////chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreCtlSignerRevocationUnknown &&
            ////X509VerificationFlags.IgnoreRootRevocationUnknown &&
            ////X509VerificationFlags.IgnoreEndRevocationUnknown &&
            ////X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown &&
            ////X509VerificationFlags.IgnoreCtlNotTimeValid;

            chain.Build(cert);

            ShowCertAndChain(cert, chain);
        }

        public static void ShowCertAndChain(X509Certificate cert, X509Chain chain)
        {
            StringBuilder sb = new StringBuilder();
            if (null != cert)
            {
                ShowX509Certificate(sb, cert);
            }

            if (null != chain)
            {
                sb.Append("-X509Chain(Start)-" + System.Environment.NewLine);
                ////sb.Append(string.Format("Cert.ChainStatus='{0}'", string.Join(",", chain.ChainStatus.ToList())) + System.Environment.NewLine);

                foreach (X509ChainStatus cstat in chain.ChainStatus)
                {
                    sb.Append(string.Format("X509ChainStatus::'{0}'-'{1}'", cstat.Status.ToString(), cstat.StatusInformation) + System.Environment.NewLine);
                }

                X509ChainElementCollection ces = chain.ChainElements;
                ShowX509ChainElementCollection(sb, ces);
                sb.Append("-X509Chain(End)-" + System.Environment.NewLine);
            }

            string result = sb.ToString();
            Console.WriteLine(result);
        }

        private static void ShowX509Extension(StringBuilder sb, int x509ExtensionCount, X509Extension ext)
        {
            sb.Append(string.Empty + System.Environment.NewLine);
            sb.Append(string.Format("--------X509ExtensionNumber(Start):{0}", x509ExtensionCount) + System.Environment.NewLine);
            sb.Append(string.Format("X509Extension.Critical='{0}'", ext.Critical) + System.Environment.NewLine);

            AsnEncodedData asndata = new AsnEncodedData(ext.Oid, ext.RawData);
            sb.Append(string.Format("Extension type: {0}", ext.Oid.FriendlyName) + System.Environment.NewLine);
            sb.Append(string.Format("Oid value: {0}", asndata.Oid.Value) + System.Environment.NewLine);
            sb.Append(string.Format("Raw data length: {0} {1}", asndata.RawData.Length, Environment.NewLine) + System.Environment.NewLine);
            sb.Append(asndata.Format(true) + System.Environment.NewLine);

            X509BasicConstraintsExtension basicEx = ext as X509BasicConstraintsExtension;
            if (null != basicEx)
            {
                sb.Append("-X509BasicConstraintsExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509BasicConstraintsExtension.CertificateAuthority='{0}'", basicEx.CertificateAuthority) + System.Environment.NewLine);
            }

            X509EnhancedKeyUsageExtension keyEx = ext as X509EnhancedKeyUsageExtension;
            if (null != keyEx)
            {
                sb.Append("-X509EnhancedKeyUsageExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509EnhancedKeyUsageExtension.EnhancedKeyUsages='{0}'", keyEx.EnhancedKeyUsages) + System.Environment.NewLine);
                foreach (Oid oi in keyEx.EnhancedKeyUsages)
                {
                    sb.Append(string.Format("------------EnhancedKeyUsages.Oid.FriendlyName='{0}'", oi.FriendlyName) + System.Environment.NewLine);
                    sb.Append(string.Format("------------EnhancedKeyUsages.Oid.Value='{0}'", oi.Value) + System.Environment.NewLine);
                }
            }

            X509KeyUsageExtension usageEx = ext as X509KeyUsageExtension;
            if (null != usageEx)
            {
                sb.Append("-X509KeyUsageExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509KeyUsageExtension.KeyUsages='{0}'", usageEx.KeyUsages) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.CrlSign='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.CrlSign) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DataEncipherment='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DataEncipherment) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DecipherOnly='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DecipherOnly) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.DigitalSignature='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.DigitalSignature) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.EncipherOnly='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.EncipherOnly) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyAgreement='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyAgreement) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyCertSign='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyCertSign) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.KeyEncipherment='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.KeyEncipherment) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.None='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.None) != 0) + System.Environment.NewLine);
                sb.Append(string.Format("X509KeyUsageExtension.KeyUsages.X509KeyUsageFlags.NonRepudiation='{0}'", (usageEx.KeyUsages & X509KeyUsageFlags.NonRepudiation) != 0) + System.Environment.NewLine);
            }

            X509SubjectKeyIdentifierExtension skIdEx = ext as X509SubjectKeyIdentifierExtension;
            if (null != skIdEx)
            {
                sb.Append("-X509SubjectKeyIdentifierExtension-" + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509SubjectKeyIdentifierExtension.Oid='{0}'", skIdEx.Oid) + System.Environment.NewLine);
                sb.Append(string.Format("X509Extension.X509SubjectKeyIdentifierExtension.SubjectKeyIdentifier='{0}'", skIdEx.SubjectKeyIdentifier) + System.Environment.NewLine);
            }

            sb.Append(string.Format("--------X509ExtensionNumber(End):{0}", x509ExtensionCount) + System.Environment.NewLine);
        }

        private static void ShowX509Extensions(StringBuilder sb, string cert2SubjectName, X509ExtensionCollection extColl)
        {
            int x509ExtensionCount = 0;
            sb.Append(string.Format("--------ShowX509Extensions(Start):for:{0}", cert2SubjectName) + System.Environment.NewLine);
            foreach (X509Extension ext in extColl)
            {
                ShowX509Extension(sb, ++x509ExtensionCount, ext);
            }

            sb.Append(string.Format("--------ShowX509Extensions(End):for:{0}", cert2SubjectName) + System.Environment.NewLine);
        }

        private static void ShowX509Certificate2(StringBuilder sb, X509Certificate2 cert2)
        {
            if (null != cert2)
            {
                sb.Append(string.Format("X509Certificate2.SubjectName.Name='{0}'", cert2.SubjectName.Name) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.Subject='{0}'", cert2.Subject) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.Thumbprint='{0}'", cert2.Thumbprint) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.HasPrivateKey='{0}'", cert2.HasPrivateKey) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.Version='{0}'", cert2.Version) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.NotBefore='{0}'", cert2.NotBefore) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.NotAfter='{0}'", cert2.NotAfter) + System.Environment.NewLine);
                sb.Append(string.Format("X509Certificate2.PublicKey.Key.KeySize='{0}'", cert2.PublicKey.Key.KeySize) + System.Environment.NewLine);

                ////List<X509KeyUsageExtension> keyUsageExtensions = cert2.Extensions.OfType<X509KeyUsageExtension>().ToList();
                ////List<X509Extension> extensions = cert2.Extensions.OfType<X509Extension>().ToList();

                ShowX509Extensions(sb, cert2.Subject, cert2.Extensions);
            }
        }

        private static void ShowX509ChainElementCollection(StringBuilder sb, X509ChainElementCollection ces)
        {
            int x509ChainElementCount = 0;
            foreach (X509ChainElement ce in ces)
            {
                sb.Append(string.Empty + System.Environment.NewLine);
                sb.Append(string.Format("----X509ChainElementNumber:{0}", ++x509ChainElementCount) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.SubjectName.Name='{0}'", ce.Certificate.SubjectName.Name) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.Issuer='{0}'", ce.Certificate.Issuer) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.Thumbprint='{0}'", ce.Certificate.Thumbprint) + System.Environment.NewLine);
                sb.Append(string.Format("X509ChainElement.Cert.HasPrivateKey='{0}'", ce.Certificate.HasPrivateKey) + System.Environment.NewLine);

                X509Certificate2 cert2 = ce.Certificate as X509Certificate2;
                ShowX509Certificate2(sb, cert2);

                ShowX509Extensions(sb, cert2.Subject, ce.Certificate.Extensions);
            }
        }

        private static void ShowX509Certificate(StringBuilder sb, X509Certificate cert)
        {
            sb.Append("-----------------------------------------------" + System.Environment.NewLine);
            sb.Append(string.Format("Cert.Subject='{0}'", cert.Subject) + System.Environment.NewLine);
            sb.Append(string.Format("Cert.Issuer='{0}'", cert.Issuer) + System.Environment.NewLine);

            sb.Append(string.Format("Cert.GetPublicKey().Length='{0}'", cert.GetPublicKey().Length) + System.Environment.NewLine);

            X509Certificate2 cert2 = cert as X509Certificate2;
            ShowX509Certificate2(sb, cert2);
        }
    }
}

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Datakom dkg 309 сброс ошибок
  • Datakam player ошибка сценария при открытии карт
  • Datagridview как изменить размер столбца
  • Datagridview data error
  • Dataframe constructor not properly called ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии