Java – How do I add a certificate to the Android truststore?

How do I add a certificate to the Android truststore?… here is a solution to the problem.

How do I add a certificate to the Android truststore?

I have a client application designed for Android. Android applications are based on XML and Java, as are our Windows server-side applications. The problem is that since we are now using Android, we have to deal with the truststore. Is there any way to dynamically add certificates to the truststore?

Client connection code:

InputStream stream = main.getResources().openRawResource(R.raw.keystore);
KeyStore trustStore;
try {
  trustStore = KeyStore.getInstance("BKS");
  trustStore.load(stream, "password".toCharArray());
} catch (Exception e) {
  e.printStackTrace();
}
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try{
  clientSocket = (SSLSocket) factory.createSocket(address, port);
}catch (Exception ex){
  ex.printStackTrace();
}

Server-side connection code:

System.setProperty("javax.net.ssl.keyStore", System.getProperty("java.io.tmpdir") + "keystore_30290.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
try {
    server = ((SSLServerSocket)factory.createServerSocket(config.port));
} catch (Exception e) {
    e.printStackTrace();
    System.out.println("Failed to successfully bind to port "+config.port+".");
    System.exit(-1);
}

Solution

Try something like this, given your trustStore:

KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
                              KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(trustStore, "password".toCharArray());
KeyManager[] keymanagers =  kmfactory.getKeyManagers();

TrustManagerFactory tmf=TrustManagerFactory
  .getInstance(TrustManagerFactory.getDefaultAlgorithm());

tmf.init(trustStore);

SSLContext sslContext=SSLContext.getInstance("TLSv1.2");

sslContext.init(keymanagers, tmf.getTrustManagers(), new SecureRandom());

SSLSocketFactory factory=sslContext.getSocketFactory();

The minimum API for this code is 16.

Related Problems and Solutions