How to bypass SSL certificate validation in Android app?

前端 未结 2 564
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 17:29

My Android application should be able to communicate to any SSL enabled servers. As my app is demo application and my customers add their own SSL server details in the app w

2条回答
  •  别那么骄傲
    2020-12-30 17:57

    quoting the solution from: https://gist.github.com/aembleton/889392

    The following code disables SSL certificate checking for any new instances of HttpsUrlConnection:

     /**
     * Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to
     * aid testing on a local box, not for use on production.
     */
    public static void disableSSLCertificateChecking() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
    
            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
    
            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
        } };
    
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
    
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
    
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } });
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题