4


I have a Bouncy Castle keystore, which I'd like to use to connect to an SSLSocketFactory. Doing this in "desktop" Java is easy, but how do you do it on the android.

It doesn't seem to make much difference whether you put in assets or res/raw - the problem comes when trying to open it up and instantiate an instance of KeyStore (java.security.KeyStore in this case) to pass to SSLSocketFactorys constructor.

Has anyone had success with this before? What's the best way of "reading" this and opening it? Any pointers or code snippets would be most welcome.

Many thanks
Don

1 Answers1

2

This should do:

import android.content.Context;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;

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

public class MyHttpClient extends DefaultHttpClient {

  final Context context;

  public MyHttpClient(Context context) {
    this.context = context;
  }

  @Override protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(
        new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", newSslSocketFactory(), 443));
    return new SingleClientConnManager(getParams(), registry);
  }

  private SSLSocketFactory newSslSocketFactory() {
    try {
      KeyStore trusted = KeyStore.getInstance("BKS");
      InputStream in = context.getResources().openRawResource(R.raw.mystore);
      try {
        trusted.load(in, "ez24get".toCharArray());
      } finally {
        in.close();
      }
      return new SSLSocketFactory(trusted);
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  }
}

ez24get would be the password for the keystore.

Donn Felker
  • 9,553
  • 7
  • 48
  • 66