Java SSL connect, add server cert to keystore programmatically

You could implement this using a X509TrustManager.

Obtain an SSLContext with

SSLContext ctx = SSLContext.getInstance("TLS");

Then initialize it with your custom X509TrustManager by using SSLContext#init. The SecureRandom and the KeyManager[] may be null. The latter is only useful if you perform client authentication, if in your scenario only the server needs to authenticate you don’t need to set it.

From this SSLContext, get your SSLSocketFactory using SSLContext#getSocketFactory and proceed as planned.

As concerns your X509TrustManager implementation, it could look like this:

TrustManager tm = new X509TrustManager() {
    public void checkClientTrusted(X509Certificate[] chain,
                    String authType)
                    throws CertificateException {
        //do nothing, you're the client
    }

    public X509Certificate[] getAcceptedIssuers() {
        //also only relevant for servers
    }

    public void checkServerTrusted(X509Certificate[] chain,
                    String authType)
                    throws CertificateException {
        /* chain[chain.length -1] is the candidate for the
         * root certificate. 
         * Look it up to see whether it's in your list.
         * If not, ask the user for permission to add it.
         * If not granted, reject.
         * Validate the chain using CertPathValidator and 
         * your list of trusted roots.
         */
    }
};

Edit:

Ryan was right, I forgot to explain how to add the new root to the existing ones. Let’s assume your current KeyStore of trusted roots was derived from cacerts (the ‘Java default trust store’ that comes with your JDK, located under jre/lib/security). I assume you loaded that key store (it’s in JKS format) with KeyStore#load(InputStream, char[]).

KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream in = new FileInputStream("<path to cacerts"");
ks.load(in, "changeit".toCharArray);

The default password to cacerts is “changeit” if you haven’t, well, changed it.

Then you may add addtional trusted roots using KeyStore#setEntry. You can omit the ProtectionParameter (i.e. null), the KeyStore.Entry would be a TrustedCertificateEntry that takes the new root as parameter to its constructor.

KeyStore.Entry newEntry = new KeyStore.TrustedCertificateEntry(newRoot);
ks.setEntry("someAlias", newEntry, null);

If you’d like to persist the altered trust store at some point, you may achieve this with KeyStore#store(OutputStream, char[].

Leave a Comment