如何解决在带有Tls 1.3的某些站点上,HTTPs请求和SslStream出现问题
我有一个简单的C#应用程序,它使用TcpClient
和SslStream
发出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 举报,一经查实,本站将立刻删除。