How to import self-signed SSL certificate to Volley on Android 4.1+

Marian Przyszedł picture Marian Przyszedł · Feb 25, 2014 · Viewed 13.2k times · Source

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.

Before, I had only android 2.3 and 3.0 devices. Now I've got also 4.1 and 4.4.

My implementation uses this approach: http://developer.android.com/training/articles/security-ssl.html (part Unknown certificate authority) On devices with Android up to 4.1 it works perfectly. SSLSocketFactory with custom certificates is passed to Volley:

Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, socketFactory));

But what happens on Android 4.1+? Why it does not work? I tried also with NullX509TrustManager like this:

private static class NullX509TrustManager implements 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 null;
    }
}

But it still does not work...

Answer

Marian Przyszedł picture Marian Przyszedł · Feb 27, 2014

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());         
}