DEV Community

Cover image for Easily configure SSL/TLS Connection
Hakky54
Hakky54

Posted on

Easily configure SSL/TLS Connection

Setting up encryption for your application, how hard can it be? I thought it would be easy, after all, all communication with modern web applications should be encrypted, right? Well, my expectations were wrong. While setting it up, I encountered a couple of hidden difficulties. For example, the configuration is vague, verbose, not straight-forward to set it up, hard to debug, and not unit-test friendly.

I want to provide a couple of examples to explain the hidden difficulties when setting up a secure connection with HTTPS and certificates in vanilla Java. For this example, I will use Apache HttpClient with mutual authentication.

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.impl.client.HttpClients;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.KeyManagerFactory;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

public class App {

    public static void main(String[] args) throws Exception {
        Path trustStorePath = Paths.get("/path/to/truststore.jks");
        InputStream trustStoreStream = Files.newInputStream(trustStorePath, StandardOpenOption.READ);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(trustStoreStream, "password".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        Path identityPath = Paths.get("/path/to/identity.jks");
        InputStream identityStream = Files.newInputStream(identityPath, StandardOpenOption.READ);
        KeyStore identity = KeyStore.getInstance(KeyStore.getDefaultType());
        identity.load(identityStream, "password".toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(identity, "password".toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(
            keyManagerFactory.getKeyManagers(), 
            trustManagerFactory.getTrustManagers(), 
            null
        );

        HttpClient httpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(new DefaultHostnameVerifier())
                .build();

        HttpGet request = new HttpGet("https://localhost:8443/api/hello");
        HttpResponse response = httpClient.execute(request);
    }
}
Enter fullscreen mode Exit fullscreen mode

As you can see this really verbose, but this is a common code snippet which is being used when setting up ssl/tls for a http client. It is also hard to unit test a SSLContext object because you can't get any information from it that will tell if the trustmanager is really initialised well and if it contains all the trusted certificates. The only way to really validate your code is by writing an integration test, where the client actually sends a request to a real server with HTTPS enabled.

Some other HTTP clients even require a different setup (e.g., Netty HttpClient, AsyncHttpClient, and Dispatch Reboot). These clients only accept an SSLContext from Netty's library instead of the one from the JDK.

I faced the same challenges as my colleagues. They also didn't enjoy setting it up. It was just a configuration that needed to be set up once, well enough to do the job, and after that, we were scared to touch it again. And it got even tougher when we wanted to use multiple keystores.

I wanted to help myself out from the verbosity make my life easier. One library to configure them all! It should be painless to use, easy to test and debug, and fun to set-it-up. The project is available at GitHub - SSLContext-Kickstart

Add the folowing maven dependency:

<dependency>
    <groupId>io.github.hakky54</groupId>
    <artifactId>sslcontext-kickstart</artifactId>
    <version>6.6.0</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Let's refactor the above code snippet while using the library.

import nl.altindag.ssl.SSLFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

import java.nio.file.Paths;

public class App {

    public static void main(String[] args) throws Exception {
        SSLFactory sslFactory = SSLFactory.builder()
                .withIdentityMaterial(Paths.get("/path/to/identity.jks"), "password".toCharArray())
                .withTrustMaterial(Paths.get("/path/to/truststore.jks"), "password".toCharArray())
                .build();

        HttpClient httpClient = HttpClients.custom()
                .setSSLContext(sslFactory.getSslContext())
                .setSSLHostnameVerifier(sslFactory.getHostnameVerifier())
                .build();

        HttpGet request = new HttpGet("https://localhost:8443/api/hello");
        HttpResponse response = httpClient.execute(request);
    }

}
Enter fullscreen mode Exit fullscreen mode

Advantages:

  • No need for low-level SSLContext configuration anymore.
  • No knowledge about SSLContext, TrustManager, TrustManagerFactory, KeyManager, KeyManagerFactory, and how to create it is needed.
  • The above classes will all be created by just providing an identity and a trustStore.
  • Create a sslcontext with multiple identities and trustStores.

Returnable values

The SSLFactory can return different kind of values for all sort of use cases. See below for the overview:

import nl.altindag.ssl.SSLFactory;
import nl.altindag.ssl.model.KeyStoreHolder;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509ExtendedTrustManager;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;

public class App {

    public static void main(String[] args) {
        SSLFactory sslFactory = SSLFactory.builder()
                .withIdentityMaterial("keystore.p12", "secret".toCharArray(), "PKCS12")
                .withTrustMaterial("truststore.p12", "secret".toCharArray(), "PKCS12")
                .build();

        SSLContext sslContext = sslFactory.getSslContext();
        HostnameVerifier hostnameVerifier = sslFactory.getHostnameVerifier();
        Optional<X509ExtendedKeyManager> keyManager = sslFactory.getKeyManager();
        Optional<X509ExtendedTrustManager> trustManager = sslFactory.getTrustManager();
        Optional<KeyManagerFactory> keyManagerFactory = sslFactory.getKeyManagerFactory();
        Optional<TrustManagerFactory> trustManagerFactory = sslFactory.getTrustManagerFactory();
        List<X509Certificate> trustedCertificates = sslFactory.getTrustedCertificates();
        List<KeyStoreHolder> identities = sslFactory.getIdentities();
        List<KeyStoreHolder> trustStores = sslFactory.getTrustStores();
        SSLSocketFactory sslSocketFactory = sslFactory.getSslSocketFactory();
        SSLServerSocketFactory sslServerSocketFactory = sslFactory.getSslServerSocketFactory();
        SSLEngine sslEngine = sslFactory.getSslEngine(host, port);
        SSLParameters sslParameters = sslFactory.getSslParameters();
        List<String> ciphers = sslFactory.getCiphers();
        List<String> protocols = sslFactory.getProtocols();
    }

}
Enter fullscreen mode Exit fullscreen mode

Tested Http Clients

The library has been tested with over 40 different http client for Java, Kotlin and Scala. See here for the complete overview

Conclusion

This was a small introduction to get you started with SSL/TLS for a Http Client. It provided an alternative setup compared to the traditional one so you as a developer can easily set it up by your self without the need of low-level knowledge. Looking for more advanced setup? Please check out all the different configurations here: Overview of configurations

Top comments (0)