Skip to content Skip to sidebar Skip to footer

How To Import Self-signed Ssl Certificate To Volley On Android 4.1+

I develop android application which uses Volley. All communication is done via HTTPS connection. Because I test it on local environment, I use self-signed certificates for Tomcat.

Solution 1:

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.

publicstaticclassNukeSSLCerts {
protectedstatic final StringTAG = "NukeSSLCerts";

publicstaticvoidnuke() {
    try {
        TrustManager[] trustAllCerts = newTrustManager[] { 
            newX509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] myTrustedAnchors = new X509Certificate[0];  
                    return myTrustedAnchors;
                }

                @OverridepublicvoidcheckClientTrusted(X509Certificate[] certs, String authType) {}

                @OverridepublicvoidcheckServerTrusted(X509Certificate[] certs, String authType) {}
            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, newSecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(newHostnameVerifier() {
            @Overridepublicbooleanverify(String arg0, SSLSession arg1) {
                returntrue;
            }
        });
    } 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. More Ref. https://newfivefour.com/android-trust-all-ssl-certificates.html

Solution 2:

I've resolved it with solution mentioned here:

http://developer.android.com/training/articles/security-ssl.html

Common Problems with Hostname Verification

by adding custom hostname verifier which returns true for my hostname in Volley project and editing HurlStack openConnection method:

if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {            
    ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory);
    ((HttpsURLConnection)connection).setHostnameVerifier(new CustomHostnameVerifier());         
}

Solution 3:

If you already have a .crt file and looking to get it attached to Volley then here are 2 simple steps to follow.

Step 1: Write this method to your code.

public SSLSocketFactory getSocketFactory(Context context)throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    // Load CAs from an InputStream (could be from a resource or ByteArrayInputStream or ...)CertificateFactorycf= CertificateFactory.getInstance("X.509");

    InputStreamcaInput=newBufferedInputStream(context.getResources().openRawResource(R.raw.myFile));
                                                   // I paste my myFile.crt in raw folder under res.
    Certificate ca;

    //noinspection TryFinallyCanBeTryWithResourcestry {
        ca = cf.generateCertificate(caInput);
        System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        caInput.close();
    }

    // Create a KeyStore containing our trusted CAsStringkeyStoreType= KeyStore.getDefaultType();
    KeyStorekeyStore= KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStoreStringtmfAlgorithm= TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactorytmf= TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManagerSSLContextsslContext= SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

    return sslContext.getSocketFactory();
}

Step 2: Just add this below line before you make any request using Volley.

HttpsURLConnection.setDefaultSSLSocketFactory(getSocketFactory(context));

Android Studio will ask you to enclose that line in try/catch for all Exceptions thrown by our method. So just let it do that.

Happy Coding!

Solution 4:

The easiest method I found is adding this class and executing it from onCreate method

new NukeSSLCerts().nuke();

It will make volley to Trust all SSL certificates

Post a Comment for "How To Import Self-signed Ssl Certificate To Volley On Android 4.1+"