4


我有一个 Bouncy Castle 密钥库,我想用它来连接 SSLSocketFactory。在“桌面”Java 中执行此操作很容易,但您如何在 android 上执行此操作。

无论您放入 assets 还是 res/raw 似乎都没有太大区别 - 当尝试打开它并实例化 KeyStore 的实例(在本例中为 java.security.KeyStore )以传递给 SSLSocketFactorys 构造函数时,问题就出现了。

以前有人成功过吗?“阅读”并打开它的最佳方式是什么?任何指针或代码片段都将受到欢迎。

非常感谢

4

1 回答 1

2

这应该这样做:

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 将是密钥库的密码。

于 2011-06-14T16:52:50.487 回答