Thursday, 18 April 2019

retrofit + okhttp on android 4 ssl

I found out that android 4 doesn't play well with ssl , when trying to contact an api with https it causes a crash

javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb8dbad20: I/O error during system call, Connection reset by peer

Here's what i tried from other similar questions:

   if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) {
        try {
            Logger.e("under lolipop");
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[] { new MyTrustManager() }, new SecureRandom());
            client.sslSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            Logger.e("HTTPS"+ e.getMessage() );
        }
    }

Which didn't effect the outcome

And

 if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) {

        try {
            client.sslSocketFactory(new TLSSocketFactory(), (X509TrustManager)trustAllCerts[0])
                    .build();
            Logger.e("SETUP TRUST SSL");
            return client.build();
        } catch (KeyManagementException e) {
            Logger.e("SETUP TRUST SSL Failed "+e.getMessage());

            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            Logger.e("SETUP TRUST SSL Failed "+e.getMessage());

            e.printStackTrace();
        }
    }
    return client.build();

}
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
    @Override
    public void checkClientTrusted(
            java.security.cert.X509Certificate[] chain,
            String authType) throws CertificateException {
    }

    @Override
    public void checkServerTrusted(
            java.security.cert.X509Certificate[] chain,
            String authType) throws CertificateException {
    }

    @Override
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return new java.security.cert.X509Certificate[0];
    }
} };

This code gives a different error :

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

Is there anyway to fix this , I must support android 4 and also use https ,

Any help will do !



from retrofit + okhttp on android 4 ssl

No comments:

Post a Comment