Adding certificate to keystore using java code

31,795

Solution 1

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.

Solution 2

I wrote small library ssl-utils-android to do so.

You can simply load any certificate by giving the filename from assets directory.

Usage:

OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());
Share:
31,795
Rohit
Author by

Rohit

Software Developer at Kiva Systems.

Updated on December 13, 2020

Comments

  • Rohit
    Rohit over 3 years

    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?

  • Rohit
    Rohit about 12 years
    Thanks for your reply Sandro. I have an addiional question please. How do you we get the certificate for a particualr url?
  • Sandro
    Sandro about 12 years
    Googling for "java download certificate from website" I found this. It seems to do exactly what you want.
  • Rohit
    Rohit about 12 years
    Thanks for the link Sandro... It really helped.
  • Nick Grealy
    Nick Grealy over 8 years
    @Sandro - link is 410 GONE
  • Sandro
    Sandro over 8 years