Issue—C#—ssl相关错误

这篇具有很好参考价值的文章主要介绍了Issue—C#—ssl相关错误。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

报错:

.net 6 :

{

"MessageTemplate": "An unhandled exception has occurred while executing the request."

"Exception": "System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.\r\n ---> System.Security.Authentication.AuthenticationException: Authentication failed because the remote party sent a TLS alert: 'HandshakeFailure'.\r\n ---> System.ComponentModel.Win32Exception (0x80090326): 接收到的消息异常,或格式不正确。\r\n --- End of inner exception stack trace ---\r\n at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)\r\n at System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken)\r\n --- End of inner exception stack trace ---\r\n at System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request)\r\n at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)\r\n at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)\r\n at Oxlias.Validation.ZhxtTokenAuthenticationHandler.GetZhxtTokenData(String uri, HttpMethod httpmethod, String zhxttoken)\r\n at Oxlias.Validation.ZhxtTokenAuthenticationHandler.AuthenticateAsync()\r\n at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at Hellang.Middleware.ProblemDetails.ProblemDetailsMiddleware.Invoke(HttpContext context)"

}

.net framework 4.6.2 :未能创建 SSL/TLS 安全通道。终止连接。


一、通过代码解决

这种只适合Client与Server双方服务器的TLS协议版本号兼容,还需要Cipher Suites(密码套件)兼容的前提下。

  1. httpclient写法

Product

Versions

.NET

Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7

.NET Framework

4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

.NET Standard

1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1

UWP

10.0

Xamarin.iOS

10.8

Xamarin.Mac

3.0

private async Task<string> GetZhxtTokenData(string uri)
{
    //HttpClientHandler clientHandler = new HttpClientHandler();
    //clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
    //clientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13 | System.Security.Authentication.SslProtocols.Tls11;

    //HttpClient client = new HttpClient(clientHandler);
    //var request = new HttpRequestMessage
    //{
    //    Method = httpmethod,
    //    RequestUri = new(uri, UriKind.Absolute)
    //};
    //request.Headers.Add("Authorization", zhxttoken);
    //var gettoken_Response = await client.SendAsync(request);
    
    //return await gettoken_Response.Content.ReadAsStringAsync();
    using (var clientHandler = new HttpClientHandler())
    {
        clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
        clientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13 | System.Security.Authentication.SslProtocols.Tls11;
        using (var httpClient = new HttpClient(clientHandler))
        {
            httpClient.DefaultRequestHeaders.Add("Authorization", "123");
            using (var response = await httpClient.GetAsync(uri))
            {
                if (response.StatusCode == HttpStatusCode.RequestTimeout)
                {
                    return HttpStatusCode.RequestTimeout.ToString();
                }
                return await response.Content.ReadAsStringAsync();
            }
        }
    }
}
  1. HttpWebRequest写法

public static string GetZhxtTokenData_HttpWebRequest(string PostUrl, string Parameters, string zhxttoken)
        {
            string content = string.Empty;
            try
            {
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;    //https 请求必需语句,http 请求可省略
                //跳过ssl验证
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                //path不是登录界面,是登录界面向服务器提交数据的界面
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(PostUrl);
                myReq.Method = "get";
                //myReq.ContentType = "application/json";
                //myReq.Connection = "keep-alive";
                myReq.Headers.Add("Cookie", "477cadb5a1f917cda5f5d9cab20f8841=42c7f20d7a509babe62c3e74995d5140; 3c343960f5dd4584c34cd6b38885cefe=000e1bf2bbd8e5ae2dabff0eb27e3b6f");
                //myReq.Headers.Add("usercode", "JRFZCX_MYFK");
                //myReq.Headers.Add("password", "*&ZHY&*0379");//&JRFZ&01
                myReq.Headers.Add("Authorization", zhxttoken);
                //填充POST数据
                if (Parameters != null)
                {
                    //转换为字节数组
                    byte[] bytesRequestData = Encoding.UTF8.GetBytes(Parameters);
                    myReq.ContentLength = bytesRequestData.Length;
                    Stream requestStream = myReq.GetRequestStream();
                    requestStream.Write(bytesRequestData, 0, bytesRequestData.Length);
                    requestStream.Close();
                }
                else
                {
                    myReq.ContentLength = 0;
                }

                //发送POST数据请求服务器
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                //获取服务器返回信息
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader reader = new StreamReader(myStream, Encoding.UTF8);
                content = reader.ReadToEnd();
                reader.Close();
                HttpWResp.Close();
            }
            catch (Exception ex)
            {
                content = ex.ToString();
            }
            return content;
        }

二、通过服务期配置解决

1.Analysis

当通过代码手段无法解决时需从问题根源寻找解决办法。

根据错误提示“System.Security.Authentication.AuthenticationException: Authentication failed because the remote party sent a TLS alert: 'HandshakeFailure'. System.ComponentModel.Win32Exception (0x80090326): 接收到的消息异常,或格式不正确。”分析出应该是两个服务器TLS版本号不兼容导致两边通信建立连接时三次握手失败。

①经查看服务器A(Red hat8.1-5) ssl密码件如下:

sh-4.4$ cat DEFAULT.pol 
# A reasonable default for today's standards. It should provide
# 112-bit security with the exception of SHA1 signatures needed for DNSSec
# and other still prevalent legacy use of SHA1 signatures.

# MACs: all HMAC with SHA1 or better + all modern MACs (Poly1305 etc)
# Curves: all prime >= 255 bits (including Bernstein curves)
# Signature algorithms: with SHA-1 hash or better (no DSA)
# TLS Ciphers: >= 128-bit key, >= 128-bit block (AES, ChaCha20, including AES-CBC)
# non-TLS Ciphers: as TLS Ciphers with added Camellia
# key exchange: ECDHE, RSA, DHE (no DHE-DSS)
# DH params size: >= 2048
# RSA params size: >= 2048
# TLS protocols: TLS >= 1.2, DTLS >= 1.2

mac = AEAD HMAC-SHA2-256 HMAC-SHA1 UMAC-128 HMAC-SHA2-384 HMAC-SHA2-512

group = X25519 X448 SECP256R1 SECP384R1 SECP521R1 \
    FFDHE-2048 FFDHE-3072 FFDHE-4096 FFDHE-6144 FFDHE-8192

hash = SHA2-256 SHA2-384 SHA2-512 SHA3-256 SHA3-384 SHA3-512 SHA2-224 SHA1

sign = ECDSA-SHA3-256 ECDSA-SHA2-256 \
       ECDSA-SHA3-384 ECDSA-SHA2-384 \
       ECDSA-SHA3-512 ECDSA-SHA2-512 \
       EDDSA-ED25519 EDDSA-ED448 \
       RSA-PSS-SHA2-256 RSA-PSS-SHA2-384 RSA-PSS-SHA2-512 \
       RSA-SHA3-256 RSA-SHA2-256 \
       RSA-SHA3-384 RSA-SHA2-384 \
       RSA-SHA3-512 RSA-SHA2-512 \
       ECDSA-SHA2-224 RSA-PSS-SHA2-224 RSA-SHA2-224 \
       ECDSA-SHA1 RSA-PSS-SHA1 RSA-SHA1

tls_cipher = AES-256-GCM AES-256-CCM CHACHA20-POLY1305 AES-256-CBC \
    AES-128-GCM AES-128-CCM AES-128-CBC

cipher = AES-256-GCM AES-256-CCM CHACHA20-POLY1305 CAMELLIA-256-GCM \
    AES-256-CTR AES-256-CBC CAMELLIA-256-CBC AES-128-GCM AES-128-CCM \
    CAMELLIA-128-GCM AES-128-CTR AES-128-CBC CAMELLIA-128-CBC

# 'RSA' is intentionally before DHE ciphersuites, as the DHE ciphersuites have
# interoperability issues in TLS.
key_exchange = ECDHE RSA DHE DHE-RSA PSK DHE-PSK ECDHE-PSK ECDHE-GSS DHE-GSS

protocol = TLS1.3 TLS1.2 DTLS1.2
ike_protocol = IKEv2

min_tls_version = TLS1.2
min_dtls_version = DTLS1.2

# Parameter sizes
mi

支持TLS1.2,也支持TLS1.3.

请求该服务器的网址显示的是TLS1.3,但另一台仅支持TLS1.2的服务器发来的请求依然可以成功创建连接并通信。

②经查看服务器B(Windows server 2012 r2) ssl密码件如下:

TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_P256
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_P384
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_P521
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384_P384
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384_P521
TLS_RSA_WITH_AES_128_CBC_SHA256
TLS_RSA_WITH_AES_256_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256_P256
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256_P384
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256_P521
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P384
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384_P521
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256_P256
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256_P384
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256_P521
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384_P384
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384_P521
TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
TLS_RSA_WITH_NULL_SHA
TLS_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_DSS_WITH_AES_128_CBC_SHA

2.solution

这个错误有些人说是请求TLS1.3的服务必须是由支持TLS1.3的客户端才能成功建立连接是不正确的。详细要看TLS1.3的服务所在的服务器是否支持TLS1.2,如果支持,只需要保证两台服务器密码套件兼容就可以成功建立连接。

我解决此错误的办法:

将服务器B密码套件修改为默认后,再次通信即解决问题。

Final、Supplementary htpps knowledge

参考链接

1、关于HTTP、HTTPS、TLS的关系:HTTPS连接是由HTTP协议与TLS协议共同完成。

Issue—C#—ssl相关错误,C#,Windows,Linux,c#,https,Powered by 金山文档

2、建立HTTPS连接不仅需要Client与Server双方的TLS协议版本号兼容,还需要Cipher Suites(密码套件)兼容。关于什么是Cipher Suites可以自行查阅资料,本文不详细展开说明。Cipher Suites的样子如图所示:文章来源地址https://www.toymoban.com/news/detail-608739.html

Issue—C#—ssl相关错误,C#,Windows,Linux,c#,https,Powered by 金山文档

到了这里,关于Issue—C#—ssl相关错误的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C# 解决 https请求 ssl证书问题,看我一篇通通解决

    废话不多说,直接上代码,实干兴邦,空谈误国!光说不贴源代码更是耍流氓! 针对旧版本的接口框架,.netformwork4.5以下,加上传统的ssl机制即可解决问题。 针对.net core版本的框架,采用ssl证书验证回调的方式,其中方案二和方案三同属于一种解决方式,方案三的更直接明了

    2024年02月16日
    浏览(50)
  • Caused by SSLError(“Can‘t connect to HTTPS URL because the SSL module is not available.“

    最近在linux系统里安装python3.11之后,使用pip安装第三方库、requests库进行网络请求都会报这个错  查找了网上很多方法,看见了一个大佬的,是在pip 的命令最后面加上: 加上之后确实可以安装第三方库了,但是在我用requests库进行请求的时候 又报了这个错  但是请求http的话

    2024年02月09日
    浏览(48)
  • windows2003系统SSL证书单站点部署https

    本文将讲解,在windows 2003操作系统下,IIS 6 环境的服务器ssl证书安装教程。 安装前,请准备好SSL证书,没有的话,可以点这里申请SSL证书 部署前请退出服务器内安装的杀毒软件(360、金山、安全狗等安全软件有可能导致SSL证书部署出错) 一、解压证书文件。证书文件解压后

    2024年02月06日
    浏览(48)
  • C# 服务HTTPS 对 请求被中止: 未能创建 SSL/TLS 安全通道报错

    [WebMethod(Description = \\\"获取HttpsPost加密服务.\\\")]         public string HTTPSPOST(String input,String sUrl)         {             Log.Add(\\\"ReceiveNotice\\\", \\\"HTTPSPOST\\\", \\\"入参sUrl:\\\" + sUrl + \\\",input:\\\" + input);             HttpWebRequest webReq = null;                            ServicePointManager.ServerCertificateV

    2024年02月11日
    浏览(42)
  • java 连接mysql,出现 Caused by: javax.net.ssl.SSLException: Received fatal alert: internal_error 错误

    问题 在本地部署tomcat项目时,卡在了“Caused by: javax.net.ssl.SSLException: Received fatal alert: internal_error” 排查         查了资料发现在MySQL5.7.41及之前的版本,安全性较低,存在任何用户都可以连接上的 test 库,所以官方在5.7.43版本加大了对隐私的保护。并且采用了默认 useSS

    2024年03月13日
    浏览(68)
  • Windows网络「SSL错误问题」及解决方案

    当我们使用了神秘力量加持网络后,可能会和国内的镜像源网站的之间发生冲突,典型的有 Python 从网络中安装包,如执行 pip install pingouin 时,受网络影响导致无法完成安装的情况: pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple ,设置了清华源镜像用于全局下载包

    2024年02月03日
    浏览(56)
  • C#调用webapi HTTPS报错:基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系--安全证书问题

    1、首先加入命名空间: using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; SSL网站,连接时需要提供证书,对于非必须提供客户端证书的情况,只要返回一个安全确认即可。我的是.NET FrameWork4.0 2、加入以下代码: 3、接收证书进行身份验

    2024年02月13日
    浏览(48)
  • Linux配置Nginx SSL支持Https配置教程

    继承上篇 Linux安装Nginx 执行: ./nginx -V 命令 如果有输出 --–with-http_ssl_module 则说明已安装好SSL模块 进入安装目录 /usr/local/nginx-1.22.1 执行安装命令: ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module 执行编译命令: make 注意:make成功后不要执行 make insta

    2024年01月18日
    浏览(41)
  • linux系统SSL证书部署https单/多站点

    以下教程为linux系统申请SSL证书,部署单/多站点https方法。如果对技术不熟悉,建议l联系服务商。 另需先申请下载SSL证书,如还没有,请先申请ssl证书。 一、linux系统单/多站点https部署方法(安装默认wdcp环境,分v3.2和v2.5教程) 说明:nginx web引擎可部署一个或多个站点,并

    2024年02月16日
    浏览(40)
  • Linux nginx实现访问,配置ssl证书实现https访问

    注意:服务器需要开通80端口 (1)alias: alias指定的路径是location的别名,不管location的值怎么写,资源的 真实路径都是 alias 指定的路径 例如:同样请求 http://xxx.com/upload/top.gif 时,在服务器查找的资源路径是: /www/wwwroot/upload/top.gif (2)root:真实的路径是root指定的值加上

    2024年02月01日
    浏览(57)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包