1. Introduction

In this tutorial, we’re going to take a look at how to use custom TrustStore in Java. We’re going first to override the default TrustStore and then explore the ways to combine certificates from multiple TrustStores. We’ll also see what the known problems and challenges are and how we can surpass them.

2. Overriding Custom TrustStore

So, first, let’s override the default TrustStore. Most likely, it’s going to be the cacerts file located in lib/security/cacerts for JDK 9 and above. For JDKs below version 9, cacerts is located under jre/lib/security/cacerts. To override it, we need to pass a VM argument -Djavax.net.ssl.trustStore with the absolute path to the TrustStore to be used as the value. For instance, if we would launch JVM like this:

java -Djavax.net.ssl.trustStore=/path/to/another/truststore.p12 app.jar

Then, instead of cacerts, Java would use /path/to/another/truststore.p12 as a TrustStore.

However, this approach has a small problem. When we override the location of the TrustStore, the default cacerts TrustStore won’t be taken into account anymore. That means, that all of the trusted CA’s certificates that come with JDK preinstalled will now no longer be available.

3. Combining Multiple TrustStores

So, to solve the problem listed above, we can do either of two things:

  • include all of the default cacerts certificates into the new TrustStore that we want to use
  • try to programmatically ask Java to look into both TrustStores during the resolution of the trust of the entity

We’ll review both approaches below as they have their pros and cons.

4. Merging TrustStores

The first approach is a relatively simple solution to the problem. In this case, we can create a new TrustStore from the default one. By doing so, we make sure that the new TrustStore will include all of the initial CA certificates:

keytool -importkeystore -srckeystore cacerts -destkeystore new_trustStore.p12 -srcstoretype PKCS12 -deststoretype PKCS12

Then, we import the certificates we need into the newly created TrustStore:

keytool -import -alias SomeSelfSignedCertificate -keystore new_trustStore.p12 -file /path/to/certificate/to/add

We can modify the initial TrustStore (meaning the cacerts itself), which might be a viable option. Other applications that rely on this exact JDK installation are the only thing to consider. They will receive these newly added certificates into default cacerts as well. That could or could not be OK, depending on the requirements.

5. Programmatically Consider Both TrustStores

This approach is a bit more complicated than the one we described. The challenge is that in JDK, there are no built-in ways to ask TrustManager (the one that decides to trust somebody) to consider multiple TrustStores. So we would have to implement it ourselves.

The first thing to do is to get the instance of the TrustManagerFactory. When we have it, we’ll be able to get the TrustManager that we need:

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);

So here, we get the default TrustManagerFactory, and then we initialize it with null as an argument. The init method initializes the TrustManagerFactory with the given TrustStore. As a side note, Java KeyStore and TrustStore are both represented by the KeyStore Java class. So when we pass null as an argument, TrustManagerFactory would initialize itself with default TrustStore (cacerts).

Once we have that, we should get the actual TrustManager from TrustManagerFactory. More specifically, we need the X509TrustManager. This TrustManager is the one that is responsible for determining whether the given x509 Certificate should be trusted or not:

X509TrustManager defaultX509CertificateTrustManager = null;
for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
    if (trustManager instanceof X509TrustManager x509TrustManager) {
        defaultX509CertificateTrustManager = x509TrustManager;
        break;
    }
}

So, we have the default JDK’s X509TrustManager, which knows only about default cacerts. Now, we need to load our own TrustStore and initialize the new TrustManagerFactory with this new TrustStore of ours:

try (FileInputStream myKeys = new FileInputStream("new_TrustStore.p12")) {
    KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    myTrustStore.load(myKeys, "new_TrustStore_pwd".toCharArray());
    trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(myTrustStore);

    X509TrustManager myTrustManager = null;
    for (TrustManager tm : trustManagerFactory.getTrustManagers()) {
        if (tm instanceof X509TrustManager x509TrustManager) {
            myTrustManager = x509TrustManager;
            break;
        }
    }
}

As we can see, we have loaded our TrustStore into a new KeyStore object using the given password. Then we get yet another default TrustManagerFactory instance (getInstance() method always returns a new object) and initialize it with our TrustStore. Then, in the same way as above, we find the X509TrustManager, which considers our TrustStore now. Now, the only thing left is configuring SSLContext to use both X509TrustManager implementations – the default one and ours.

6. Reconfiguring SSLContext

Now, we need to teach the SSLContext to use our 2 X509TrustManagers. The problem is that we cannot pass them separately into SSLContext. That is because SSLContext, surprisingly, will use only the first X509TrustManager it finds and will ignore the rest*.* To overcome this, we need to create a single finalX509TrustManager that is a wrapper over our two X509TrustManagers:

X509TrustManager finalDefaultTm = defaultX509CertificateTrustManager;
X509TrustManager finalMyTm = myTrustManager;

X509TrustManager wrapper = new X509TrustManager() {
    private X509Certificate[] mergeCertificates() {
        ArrayList<X509Certificate> resultingCerts = new ArrayList<>();
        resultingCerts.addAll(Arrays.asList(finalDefaultTm.getAcceptedIssuers()));
        resultingCerts.addAll(Arrays.asList(finalMyTm.getAcceptedIssuers()));
        return resultingCerts.toArray(new X509Certificate[resultingCerts.size()]);
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return mergeCertificates();
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        try {
            finalMyTm.checkServerTrusted(chain, authType);
        } catch (CertificateException e) {
            finalDefaultTm.checkServerTrusted(chain, authType);
        }
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        finalDefaultTm.checkClientTrusted(mergeCertificates(), authType);
    }
};

And then initialize the TLS SSLContext with our wrapper:

SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { wrapper }, null);
SSLContext.setDefault(context);

We’re also setting this SSLContext as a default one. This is just in case since most of the clients that want to establish a secure connection would use TLS SSLContext. This serves as a backup option, though. We’re finally done.

7. Conclusion

In this article, we explored the ways how to use certificates from different TrustStores in one Java application.

Unfortunately, in Java, if we specify the TrustStore location from the command line, this would instruct Java to use only the specified TrustStore. So our options are either to modify the default cacerts TrustStore file or create a brand new TrustStore file that would contain all required CA certificate entries. A more complex approach is to force SSLContext to consider both TrustStores programmatically.

Still, all of these options would work, and we should use the one that fits our requirements.

As always, the entire source code for this article is available over on GitHub.