如何将证书添加到Android信任库?

时间:2016-07-02 16:59:50

标签: java android ssl

我有一款专为Android设计的客户端应用。 Android应用程序基于XML和Java,我们的Windows服务器端应用程序也是如此。问题是,由于我们现在正在使用Android,我们必须处理信任存储。有没有办法动态地将证书添加到信任存储区?

客户端连接代码:

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

服务器端连接代码:

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

1 个答案:

答案 0 :(得分:2)

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

此代码的最小API为16。