首页 > 其他分享 >低版本Android发送https请求,Android4.4.2启用TLSv1.2,Android4.4.2发送https请求报错,Android4 SSL handshake aborted

低版本Android发送https请求,Android4.4.2启用TLSv1.2,Android4.4.2发送https请求报错,Android4 SSL handshake aborted

时间:2024-12-24 10:57:17浏览次数:4  
标签:String Android4.4 发送 delegate https import Override new public

参考:https://blog.csdn.net/weixin_54087854/article/details/134625241
https://blog.csdn.net/weixin_35647799/article/details/117684065
Android4.4.2发送https请求时,出现错误:
javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb7eabc88: Failure in SSL library, usually a protocol error    error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version (external/openssl/ssl/s23_clnt.c:741 0xa4fb8d5c:0x00000000)

SSLSocket的setEnabledProtocols配置支持TLSv1.1,TLSv1.2协议
辅助类

import android.os.Build;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class SSLSocketFactoryCompat extends SSLSocketFactory {
    private static final String[] TLS_V12_ONLY = {"TLSv1.2"};

    private final SSLSocketFactory delegate;

    public SSLSocketFactoryCompat() throws KeyManagementException, NoSuchAlgorithmException {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, null, null);
        delegate = sc.getSocketFactory();
    }

    public SSLSocketFactoryCompat(SSLSocketFactory delegate) {
        if (delegate == null) {
            throw new NullPointerException();
        }
        this.delegate = delegate;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return delegate.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return delegate.getSupportedCipherSuites();
    }

    private Socket enableTls12(Socket socket) {
        if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 20) {
            if (socket instanceof SSLSocket) {
                ((SSLSocket) socket).setEnabledProtocols(TLS_V12_ONLY);
            }
        }
        return socket;
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        return enableTls12(delegate.createSocket(s, host, port, autoClose));
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException {
        return enableTls12(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
        return enableTls12(delegate.createSocket(host, port, localHost, localPort));
    }

    @Override
    public Socket createSocket(InetAddress host, int port) throws IOException {
        return enableTls12(delegate.createSocket(host, port));
    }

    @Override
    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
        return enableTls12(delegate.createSocket(address, port, localAddress, localPort));
    }
}

TrustAllCerts类

import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class TrustAllCerts implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) {}

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) {}

    @Override
    public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}
}

创建OkHttpClient方法

            OkHttpClient okHttpClient = null;
            //日志拦截器
            LoggingInterceptor loggingInterceptor = new LoggingInterceptor();
            GzipRequestInterceptor gzipRequestInterceptor = new GzipRequestInterceptor();

            // 邢帅杰 update 2023-08-08 新增用于https证书信任
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.connectTimeout(timeout, TimeUnit.SECONDS);//响应时间
            builder.readTimeout(timeout, TimeUnit.SECONDS);//读取时间
            builder.addInterceptor(loggingInterceptor);//添加日志拦截器
            // 信任https证书
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            //信任所有https证书
            TrustAllCerts trustAllCerts = new TrustAllCerts();
            //安卓系统版本号
            String androidVer = String.valueOf(android.os.Build.VERSION.RELEASE);//安卓4:4.4.2
            //sdk版本号
            int sdkVer = Build.VERSION.SDK_INT;//安卓4:19
            //创建管理器
            //如果是安卓4,强制启用TLSv1.2
            try {
                SSLContext sslContext = null;
                SSLSocketFactory factory = null;
                if (sdkVer == 19 || "4.4.2".equals(androidVer) || androidVer.startsWith("4.")) {
                    sslContext = SSLContext.getInstance("TLSv1.2");
                    sslContext.init(null, new TrustManager[]{trustAllCerts}, new SecureRandom());
                    //为OkHttpClient设置sslSocketFactory
                    factory = new SSLSocketFactoryCompat(sslContext.getSocketFactory());
                } else {
                    sslContext = SSLContext.getInstance("TLS");
                    sslContext.init(null, new TrustManager[]{trustAllCerts}, new SecureRandom());
                    factory = sslContext.getSocketFactory();
                }
                builder.sslSocketFactory(factory, trustAllCerts);
                okHttpClient = builder.build();
            } catch (Exception e) {
                e.printStackTrace();
            }

 

标签:String,Android4.4,发送,delegate,https,import,Override,new,public
From: https://www.cnblogs.com/xsj1989/p/18626880

相关文章

  • 华为、华三、思科高级网络工程师必经之路(2)我们的爱如同TCP连接,始终可靠,永不掉线——
    欢迎各位彦祖与热巴畅游本人专栏与博客你的三连是我最大的动力以下图片仅代表专栏特色[点击箭头指向的专栏名即可闪现]专栏跑道一➡️网络空间安全——全栈前沿技术持续深入学习 专栏跑道二➡️ 24NetworkSecurity-LJS ​​ ​专栏跑道三 ➡️ MYSQL......
  • 邮件加密发送和接收
    实验目的与要求1.帮助学生掌握邮件加密发送和解密接收的简易方法,掌握设置方法,提高专业技能和专业素养。2.要求学生掌在不一样的环境里实现邮件加密发送和解密接收。实验原理与内容实现安全电子邮件案例.流程大致为:用户向CA申请一个用于邮件加密的数字证书:然后将数字......
  • Camstar禁用SSL,使用Http替代Https登录Portal
    前提:1.Camstar安装正常并正常可以通过浏览器打开登录2.适用Camstar版本:8.3/8.5/8.9(问就是别的版本没用过)默认安装完成的地址:https://localhost/CamstarPortal/default.htm#/loginStep1:进入系统注册表修改相关信息CamstarInSiteServer进入注册表:regedit找到路......
  • CentOS HTTPS自签证书访问失败问题的排查与解决全流程
    sudocpharbor.crt/usr/local/share/ca-certificates/sudoyuminstall-yca-certificatessudoupdate-ca-trustforce-enablesudoupdate-ca-trustextract但是访问https://172.16.20.20仍然报错*Abouttoconnect()to172.16.20.20port443(#0)*Trying1......
  • Nginx 配置 https 访问
    一、准备条件1、安装Nginx,参考:Linux离线安装Nginx2、生成ssl证书,参考:自签名SSL证书生成二、配置httpscd/usr/local/nginx/confvinginx.conf##添加如下内容:server{listen443ssl;server_namelocalhost;ssl_certificatecert.crt;##......
  • C# 使用smtp.qq.com邮箱服务发送邮件
    1、开启SMTP服务,相当于授权过程(开启后,才可以通过这个模拟发送)位置:设置-->账号-->账号安全-->POP3/SMTP服务-->开启 2、编写发送邮箱邮件代码(引用:System.Net,System.Net.Mail)///<summary>///邮件发送帮助类///</summary>publicclassSMTPSendHelper......
  • https双向认证
    一、https双向认证原理双向认证流程客户端发起建立HTTPS连接请求,将SSL协议版本的信息发送给服务端;服务器端将本机的公钥证书(server.crt)发送给客户端;客户端读取公钥证书(server.crt),取出了服务端公钥;客户端将客户端公钥证书(client.crt)发送给服务器端;服务器端使用根证书......
  • https://github.com/mvysny/vok-helloworld-app修改内容
    build.gradle.kts:importorg.gradle.api.tasks.testing.logging.TestExceptionFormatimportorg.jetbrains.kotlin.gradle.dsl.JvmTargetimportorg.jetbrains.kotlin.gradle.tasks.KotlinCompileplugins{kotlin("jvm")version"2.1.0"......
  • 企业微信群机器人发送消息通知
    开发文档官方开发文档文本类型直接发送消息及通知人即可defsend_text_msg(bot_key,msg,mentioned_list=None,mentioned_mobile_list=None,at_all=False):'''向指定机器人发送文本消息:parambot_key:企微机器人key:parammsg:文本消息:param......
  • 深入解析:Nginx通过一个域名配置多个HTTPS项目的实现与优化
    目录引言Nginx基础知识什么是NginxNginx的核心功能多项目部署的需求分析实现一个域名配置多个项目准备工作配置HTTPS的基本步骤配置多个项目的两种方式Nginx配置文件详解基于路径区分项目基于子域名区分项目HTTPS配置中的注意事项证书生成与管理多项目使用单一证书......