Scottie9811
Scottie9811

Reputation: 53

How to add a certificate to the Android trust store?

I got a client app designed for Android. Android apps are based around XML and Java, well so is our server side app for Windows. The issue is that since we are working with Android now, we have to deal with the trust store. Is there any way to add a certificate to the trust store dynamically?

Client side 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);
}

Upvotes: 3

Views: 7280

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006574

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();

Minimum API is 16 for this code.

Upvotes: 2

Related Questions