Android: opening a keystore as an asset to create an SSLSocketFactory


I have a Bouncy Castle repository that I would like to use to connect to SSLSocketFactory. Doing this on โ€œdesktopโ€ Java is simple, but how do you do it on Android.

It doesn't seem to matter much whether you get into assets or res / raw - the problem arises when you try to open it and create an instance of KeyStore (in this case java.security.KeyStore) to go to the SSLSocketFactorys Constructor.

Has anyone had success with this before? What is the best way to โ€œreadโ€ this and open it? Any pointers or code snippets would be most welcome.

Thank you very much
don

+3
source share
1

:

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 .

+2

Source: https://habr.com/ru/post/1794146/


All Articles