javaandroidsslhttpsurlconnection

How to ADD self-signed certificates to default certificates in HttpsURLConnection


Good morning.

My problem is, I want to create a HttpsURLConnection that accepts default trusted certificates but also my self-signed certificated.

After looking around in Internet, I found a lot of similar questions, but not exactly what I want.

In particular, a good code is here.

This is pretty much what I want, but with a difference: They will trust ONLY the self-signed certificates, I want to trust ALSO the self-signed certificates.

Basically I don't want to start from an empty KeyStore, I would like to get the default keystore, whatever/wherever it is, something that already contains the default certificates in my OS.

PS: I am working in Android.

Thanks to everyone


Solution

  • You basically want to use the default trusted certificates as well as your own trusted certificates. Similar question and answers have been provided here: Registering multiple keystores in JVM

    I also ran into the same issue and found the answer of Code a Ray really useful. After using his code snippet for multiple projects I created a library out of it. You can find it here: sslcontext-kickstart

    For your use case the following snipper with your certificates wrapped in a truststore file should do the trick:

    SSLFactory sslFactory = SSLFactory.builder()
        .withDefaultTrustMaterial()
        .withTrustMaterial("my-truststore.jks", "password".toCharArray())
        .build();
    
    HttpsURLConnection httpsURLConnection = (HttpURLConnection) new URL(url).openConnection();
    httpsURLConnection.setHostnameVerifier(sslFactory.getHostnameVerifier());
    httpsURLConnection.setSSLSocketFactory(sslFactory.getSslContext().getSocketFactory());