当前位置:   article > 正文

Android 4.4 以下,OkHttp访问Https报错,设置了sslSocketFactory仍无效的解决方法_external/openssl/ssl/s23_clnt.c:744 0x5294dcfc:0x0

external/openssl/ssl/s23_clnt.c:744 0x5294dcfc:0x00000000

背景

Android 4.4 及以下,使用 OkHttp 发送 Https 请求,报以下错误:

    javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x6b712c90: Failure in SSL library, usually a protocol error
    error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x68111cd4:0x00000000)
        at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:448)
        at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302)
        at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270)
        at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)
     Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x6b712c90: Failure in SSL library, usually a protocol error
    error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x68111cd4:0x00000000)
        at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
        at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)
        	... 23 more
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

一、确保OkHttp的Https配置正确

首先配制好 sslSocketFactory 和 hostnameVerifier:

import android.annotation.SuppressLint
import java.net.InetAddress
import java.net.Socket
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class MySSLSocketFactory(tm: TrustManager = TrustAllTrustManager()) : SSLSocketFactory() {
    var internalSSLSocketFactory: SSLSocketFactory
    var context: SSLContext = SSLContext.getInstance("TLSv1.1")

    init {
        context.init(null, arrayOf(tm), null)
        internalSSLSocketFactory = context.socketFactory
    }


    override fun getDefaultCipherSuites(): Array<String> {
        return internalSSLSocketFactory.defaultCipherSuites
    }

    override fun createSocket(s: Socket?, host: String?, port: Int, autoClose: Boolean): Socket {
        val sslSocket = context.socketFactory?.createSocket(s, host, port, autoClose) as SSLSocket
        sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1")
        return sslSocket
    }

    override fun getSupportedCipherSuites(): Array<String> {
        return internalSSLSocketFactory.supportedCipherSuites
    }

    override fun createSocket(host: String?, port: Int): Socket {
        val sslSocket = context.socketFactory?.createSocket(host, port) as SSLSocket
        sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1")
        return sslSocket
    }

    override fun createSocket(host: String?, port: Int, localHost: InetAddress?, localPort: Int): Socket {
        val sslSocket = context.socketFactory?.createSocket(host, port, localHost, localPort) as SSLSocket
        sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1")
        return sslSocket
    }

    override fun createSocket(host: InetAddress?, port: Int): Socket {
        val sslSocket = context.socketFactory?.createSocket(host, port) as SSLSocket
        sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1")
        return sslSocket
    }

    override fun createSocket(address: InetAddress?, port: Int, localAddress: InetAddress?, localPort: Int): Socket {
        val sslSocket = context.socketFactory?.createSocket(address, port, localAddress, localPort) as SSLSocket
        sslSocket.enabledProtocols = arrayOf("TLSv1.2", "TLSv1.1")
        return sslSocket
    }

    @SuppressLint("CustomX509TrustManager", "TrustAllX509TrustManager")
    class TrustAllTrustManager : X509TrustManager {
        @Throws(CertificateException::class)
        override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
        }

        @Throws(CertificateException::class)
        override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
        }

        override fun getAcceptedIssuers(): Array<X509Certificate> {
            return arrayOf()
        }
    }
}

public class SSLSocketClient {
    //获取这个SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //获取TrustManager
    private static TrustManager[] getTrustManager() {
        return new TrustManager[]{new 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];
            }
        }};
    }

    //获取HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116

在OkHttp中使用:

    val tm = TrustAllTrustManager()
    val client = OkHttpClient.Builder()
        .sslSocketFactory(
            MySSLSocketFactory(tm), tm
        )
        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
        .build()
    val request = Request.Builder().url(url).build()
    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            Log.w(TAG, "onFailure: ", e)
            onResult(Log.getStackTraceString(e))
        }

        override fun onResponse(call: Call, response: Response) {
            val result = response.body()?.string()
            onResult(result)
        }
    })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

二、仍然报错的解决方案

如果通过以上的配置,仍然报 Failure in SSL library, usually a protocol error 的错,则有以下两种解决方案:

1. 降级OkHttp

将 OkHttp 降级到 3.9.0,即可正常请求。

2. 配置ConnectionSpec

OkHttpClient 创建的过程中,添加 ConnectionSpec 的配置,如下:

    // ConnectionSpec的配置
    val spec = ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
        .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
        .cipherSuites(
            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
            CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
            CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
        )
        .build()

    val tm = TrustAllTrustManager()
    val client = OkHttpClient.Builder()
        .connectionSpecs(Collections.singletonList(spec))
        .sslSocketFactory(
            MySSLSocketFactory(tm), tm
        )
        .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
        .build()
    val request = Request.Builder().url(url).build()
    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            Log.w(TAG, "onFailure: ", e)
            onResult(Log.getStackTraceString(e))
        }

        override fun onResponse(call: Call, response: Response) {
            val result = response.body()?.string()
            onResult(result)
        }
    })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/210487
推荐阅读
相关标签
  

闽ICP备14008679号