Accept server's self-signed ssl certificate in Java client

后端 未结 12 1680
日久生厌
日久生厌 2020-11-22 00:04

It looks like a standard question, but I couldn\'t find clear directions anywhere.

I have java code trying to connect to a server with probably self-signed (or expir

12条回答
  •  日久生厌
    2020-11-22 00:26

    Trust all SSL certificates:- You can bypass SSL if you want to test on the testing server. But do not use this code for production.

    public static class NukeSSLCerts {
    protected static final String TAG = "NukeSSLCerts";
    
    public static void nuke() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[] { 
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        X509Certificate[] myTrustedAnchors = new X509Certificate[0];  
                        return myTrustedAnchors;
                    }
    
                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {}
    
                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                }
            };
    
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
        } catch (Exception e) { 
        }
    }
    

    }

    Please call this function in onCreate() function in Activity or in your Application Class.

    NukeSSLCerts.nuke();
    

    This can be used for Volley in Android.

提交回复
热议问题