在带有Tls 1.3的某些站点上,HTTPs请求和SslStream出现问题

问题描述

我有一个简单的C#应用​​程序,它使用TcpClientSslStream发出HTTPs请求。一切正常,除了使用TLS 1.3的某些网站出现故障。我将项目升级到.Net Framework 4.8,也慢慢阅读了https://docs.microsoft.com/es-es/dotnet/framework/network-programming/tls,但无法实现解决方案。

我正在使用Windows 10 64位编译19041.508。

一个我可以提供的最小代码示例:

using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Security;
using System.Net.sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
        private void button1_Click(object sender,EventArgs e)
        {
            string hostname = "stackoverflow.com";

            using (TcpClient tcpClient = new TcpClient())
            {
                tcpClient.Connect(hostname,443);

                //HTTP request headers
                string reqString = "GET / HTTP/1.1" + "\r\n";
                reqString += "Host: " + hostname + "\r\n";
                reqString += "Connection: Close\r\n\r\n";
                byte[] header_bytes = Encoding.ASCII.GetBytes(reqString);

                using (SslStream sslStream = new SslStream(tcpClient.GetStream(),false,new RemoteCertificateValidationCallback(ValidateServerCertificate),null))
                {
                    sslStream.AuthenticateAsClient(hostname,null,SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13,false);
                    sslStream.Write(header_bytes,header_bytes.Length);

                    string response = "";
                    using (var memory = new MemoryStream())
                    {
                        sslStream.copyTo(memory,81920);
                        memory.Position = 0;
                        byte[] data = memory.ToArray();
                        response = Encoding.UTF8.GetString(data);
                        textBox1.Text = response;
                    }
                }
            }
        }

        //Validate certificates
        public static bool ValidateServerCertificate(
        object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }

如果您尝试使用主机名stackoverflow.com,它可以工作,但是如果您使用例如manga1001.com,则它会失败并抛出异常。例外详情:

System.Security.Authentication.AuthenticationException: A call to sspI Failed,see inner exception.

希望有人可以帮我解决这个问题,我花了很多时间,但没有找到解决方法

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)