Adding certificate to keystore using java code

Rohit picture Rohit · Apr 9, 2012 · Viewed 28.3k times · Source

I'm trying to establish a https connection using the server's .cer certificate file. I am able to manually get the certificate file using a browser and put it into the keystore using keytool. I can then access the keystore using java code, obtain the certificate i added to the keystore and connect to the server.

I now however want to implement even the process of getting the certificate file and adding it to my keystore using java code and without using keytool or browser to get certificate.

Can someone please tell me how to approach this and what I need to do?

Answer

Sandro picture Sandro · Apr 9, 2012

Edit: This seems to do exactly what you want.

Using the following code it is possible to add a trust store during runtime.

import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

public class SSLClasspathTrustStoreLoader {
    public static void setTrustStore(String trustStore, String password) throws Exception {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = SSLClasspathTrustStoreLoader.class.getResourceAsStream(trustStore);
        keystore.load(keystoreStream, password.toCharArray());
        trustManagerFactory.init(keystore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustManagers, null);
        SSLContext.setDefault(sc);
    }
}

I used this code to establish a secure LDAP connection with an active directory server.

This could also be usful, at the bottom there is a class, which is able to import a certificate during runtime.