83

My customer has informed my of issues with their SSL and Internet Explorer. They said they get trust issues when accessing the URL.

I am accessing JSON through HTTPS. The website sits on one server and I am using the console app on my local machine. I am trying to bypass the SSL Cert, however, my code still fails.

Can I alter HttpWebRequest to fix this problem?

I get this error using this code:

    // You must change the URL to point to your Web server.
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "GET";
        req.AllowAutoRedirect = true;

        // allows for validation of SSL conversations
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };


        WebResponse respon = req.GetResponse();
        Stream res = respon.GetResponseStream();

        string ret = "";
        byte[] buffer = new byte[1048];
        int read = 0;
        while ((read = res.Read(buffer, 0, buffer.Length)) > 0)
        {
            //Console.Write(Encoding.ASCII.GetString(buffer, 0, read));
            ret += Encoding.ASCII.GetString(buffer, 0, read);
        }
        return ret;
Joseph Anderson
  • 4,114
  • 4
  • 45
  • 99

15 Answers15

164

I had to enable other security protocol versions to resolve the issue:

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
        | SecurityProtocolType.Tls11
        | SecurityProtocolType.Tls12
        | SecurityProtocolType.Ssl3;
glm
  • 2,131
  • 2
  • 13
  • 10
  • Lost 2 days to realize it, decompiled HttpWebRequest class, but only switching to TLS helped. – nikolai.serdiuk Jan 26 '15 at 13:30
  • nice to know multiple values can be set like that (as of course can be done with enum). – Nicholas Petersen Oct 08 '15 at 17:23
  • 2
    @NicholasPetersen FYI this can only be done with enums with the Flags attribute. See https://msdn.microsoft.com/en-us/library/system.flagsattribute(v=vs.110).aspx – defines Feb 07 '17 at 16:10
  • I'm using ASP.NET MVC 4 and your snippet does not work for me. But I follow the error message and make it work by removing the .Tls11 and .Tls12. Thanks. – Doan Vu Mar 29 '17 at 09:34
  • For anyone using PaymentExpress sample code and their new UAT environment (https://uat.paymentexpress.com/pxaccess/pxpay.aspx) it needs to use TLS 1.2 and newer. You must have the line of code in the answer provided above just before 'var requestStream = webReq.GetRequestStream();' – Gwasshoppa Oct 24 '17 at 01:54
  • ASP.NET folks - Add this to your Global.asax.cs typically in your App_code folder for Application_Start method and the appropriate namespaces. Worked like a charm. This error started occurring after Windows .NET security updates for March 2018 – moto_geek Apr 10 '18 at 16:59
  • keep in mind that `ServicePointManager.SecurityProtocol` is static. If you, like me, have to make one web request to an older TLS1.0 endpoint then you'll need to set `ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;` and then somewhere else in the app, make a request of a newer TLS 1.2 endpoint, you';ll need to change this value: `ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;`. You can't just use flags attribute to set it all all types and expect it to work. You need to be specific. – Matt Kocaj May 10 '18 at 06:26
  • This worked great! By default we only had Tls and Ssl3 and Azure just stopped supporting them (without any notice as far as we know). So adding Tls11 and Tls12 worked. – Flipbed Mar 21 '19 at 15:29
  • Does't help if on server side is accepted only cipers with SHA256 or SHA384 hash. – Libor B. Oct 17 '19 at 10:03
  • I'd rather upgrade to .net 4.8 or beyond - but for places where that's not possible or interim, this is a good idea. So e.g SSIS is a place where I couldn't easily upgrade and a regedit seemed to microsofts 'solution' – Richard Housham Jun 01 '22 at 09:44
29

I enabled logging using this code:

http://blogs.msdn.com/b/dgorti/archive/2005/09/18/471003.aspx

The log was in the bin/debug folder (I was in Debug mode for my console app). You need to add the security protocol type as SSL 3

I received an algorithm mismatch in the log. Here is my new code:

        // You must change the URL to point to your Web server.
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "GET";
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;


        // Skip validation of SSL/TLS certificate
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };


        WebResponse respon = req.GetResponse();
        Stream res = respon.GetResponseStream();

        string ret = "";
        byte[] buffer = new byte[1048];
        int read = 0;
        while ((read = res.Read(buffer, 0, buffer.Length)) > 0)
        {
            Console.Write(Encoding.ASCII.GetString(buffer, 0, read));
            ret += Encoding.ASCII.GetString(buffer, 0, read);
        }
        return ret;
thelem
  • 2,642
  • 1
  • 24
  • 34
Joseph Anderson
  • 4,114
  • 4
  • 45
  • 99
  • 9
    It is important to mention that a bug (http://security.stackexchange.com/a/70724) has been found on SSLv3 and most implementations will no longer allow it. You should use `SecurityProtocolType.Tls12` instead. – douglaslps Oct 21 '14 at 15:47
  • 11
    Be aware that using this solution implies that *any* server certificate will be accepted as valid (since `ServerCertificateValidationCallback` always returns true) – Aurélien Gasser May 21 '15 at 09:27
  • troubleshooting using `Method = "HEAD"` ? – Kiquenet Apr 18 '18 at 22:00
15

Similar to an existing answer but in PowerShell:

[System.Net.ServicePointManager]::SecurityProtocol = `
[System.Net.SecurityProtocolType]::Tls11 -bor 
[System.Net.SecurityProtocolType]::Tls12 -bor `   
[System.Net.SecurityProtocolType]::Tls -bor `
[System.Net.SecurityProtocolType]::Ssl3

Then calling Invoke-WebRequest should work.

Got this from anonymous feedback, good suggestion: Simpler way to write this would be:

[System.Net.ServicePointManager]::SecurityProtocol = @("Tls12","Tls11","Tls","Ssl3")

Found this fantastic and related post by Jaykul: Validating Self-Signed Certificates From .Net and PowerShell

Craig - MSFT
  • 596
  • 9
  • 13
  • Answers move around depending on how you sort them, and by default, how many votes they have. Consider referencing the other answer by its author. – Litty Feb 17 '16 at 21:42
  • woot thank you for this post... I was perplexed on how to set the protocol type. – Thom Schumacher Dec 06 '17 at 21:18
7

This could be caused by a few things (most likely to least likely):

  1. The server's SSL certificate is untrusted by the client. Easiest check is to point a browser at the URL and see if you get an SSL lock icon. If you get a broken lock, icon, click on it to see what the issue is:

    1. Expired dates - get a new SSL certificate
    2. Name does not match - make sure that your URL uses the same server name as the certificate.
    3. Not signed by a trusted authority - buy a certificate from an authority such as Verisign, or add the certificate to the client's trusted certificate store.
    4. In test environments you could update your certificate validator to skip access checks. Don't do this in production.
  2. Server is requiring Client SSL certificate - in this case you would have to update your code to sign the request with a client certificate.

Jon Wagner
  • 667
  • 4
  • 6
  • 2
    All good except the last point. The client certificate isn't used to sign the request, it is provided in the handshake, so it needs to be made available to the transport before the connnection is opened. How that is done in Javascript is left as an exercise for the reader ;-) – user207421 May 30 '12 at 22:08
  • How do I sign with a client certificate? I added ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }, but it still gives me the error. – Joseph Anderson May 31 '12 at 14:28
  • Your comment "requiring Client SSL certificate" helped me look at the actually certificate I was sending....and thus my new answer with this question. A "duh" moment now, but now a few hours ago! Thx – granadaCoder Sep 13 '17 at 17:22
6

For .Net v4.0 I noticed, setting the value of ServicePointManager.SecurityProtocol to (SecurityProtocolType)3072 but before creating the HttpWebRequest object helped.

sameerfair
  • 406
  • 7
  • 13
  • Upvote for reminding me to set the SecurityProtocol before creating the HttpWebrequest object, but why... why would you cast an int instead of spelling out the enum values? – Nathan Jul 28 '20 at 17:29
  • Or just use the enum value SecurityProtocolType.Tls12 from System.Net – Mark A. Durham Dec 10 '20 at 17:18
  • The above suggestion worked for me. The solution should be accepted. You can find my code lines below the comment section – Sangamesh Arali Dec 15 '20 at 09:31
4

Also received "Could not create SSL/TLS secure channel" error. This is what worked for me. System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)3072;

Jeffrey DeMuth
  • 131
  • 1
  • 3
2

Unfortunately none of the answers mentioned above worked for me. Below listed code did a wonder for me. In case if it helps someone.

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

And this must set before creating the HttpWebRequest.

shas
  • 1,301
  • 2
  • 10
  • 10
1

Please see below link once. SecurityProtocolType.SsL3 is now old.

http://codemust.com/poodle-vulnerability-fix-openssl/

Rajesh Pathakoti
  • 659
  • 5
  • 10
1

Define SecurityProtocol as below.This sorted the issue in my case

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

P.Githinji
  • 1,459
  • 11
  • 5
0

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);
        }
    }
}
granadaCoder
  • 26,328
  • 10
  • 113
  • 146
0

From @sameerfair comment

"For .Net v4.0 I noticed, setting the value of ServicePointManager.SecurityProtocol to (SecurityProtocolType)3072 but before creating the HttpWebRequest object helped."

The above suggestion worked for me. Below are my code lines which are worked for me

var securedwebserviceurl="https://somedomain.com/service";
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11;
// Skip validation of SSL/TLS certificate
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var httpWebRequest = (HttpWebRequest)WebRequest.Create(securedwebserviceurl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ProtocolVersion= HttpVersion.Version10;
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
string responseFromServer = streamReader.ReadToEnd();
}
Sangamesh Arali
  • 101
  • 1
  • 7
0

This worked for me :

ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                   | SecurityProtocolType.Tls11
                   | SecurityProtocolType.Tls12
                   | SecurityProtocolType.Ssl3;
Annia Martinez
  • 2,442
  • 1
  • 12
  • 9
0

This worked for me :

ServicePointManager.ServerCertificateValidationCallback = (snder, cert, chain, error) => true;

if it doesn't work, it may work with other solutions like this :

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = (snder, cert, chain, error) => true;
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
0

It can be useful when the server where your application is hosted supports only Tls 1.2. In this case you'll need remove old insecure protocols, and keep only Tls 1.2:

// Remove insecure protocols (SSL3, TLS 1.0, TLS 1.1)
ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls;
ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls11;

// Add TLS 1.2
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

nandox
  • 81
  • 5
0

This error showed up for me as a symptom of AppLocker blocking a PowerShell script. As soon as I ran it from a whitelisted location, no more issues.

KERR
  • 1,312
  • 18
  • 13