banner
指数爆炸

指数爆炸

我做了对饭 !
github
bilibili

How to ignore SSL certificate verification: javax.net.ssl.SSLHandshakeException

// Complete error message
javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

This error means that during the SSL/TLS handshake process, the client is unable to verify the server's SSL certificate. The reasons for this are:

  • Server certificate not trusted by the client: The server's SSL certificate may not be issued by a trusted certificate authority (CA) recognized by the client, or the certificate may have expired.
  • Network issues: In some cases, if there are network connectivity problems between the client and server, it can also result in a failed SSL handshake.

Resolving certificate issues#

The solution lies on the server side, but usually we are calling someone else's API and we cannot modify their SSL certificate, right?

Resolving it ourselves#

To resolve it ourselves, we can ignore SSL certificate verification, but this will decrease security and is not recommended for use, unless absolutely necessary.

// Create an OkHttpClient that does not require SSL verification
public static OkHttpClient getClient() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustManagers = 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];
                }
            }
    };

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagers, new SecureRandom());

    final OkHttpClient client = new OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0])
            .hostnameVerifier((s, sslSession) -> true)
            .build();

    return client;
}

private final OkHttpClient client = getClient();

// Now we have an OkHttpClient object that ignores SSL certificate verification
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.