[url=http://stackup.iteye.com/blog/1111547]android https之一[/url]
[url=http://stackup.iteye.com/blog/1111548]android https之二[/url]
[url=http://stackup.iteye.com/blog/1111550]android https之三[/url]
[url=http://stackup.iteye.com/blog/1111548]android https之二[/url]
[url=http://stackup.iteye.com/blog/1111550]android https之三[/url]
private static void installCert(String host, int port, String passwd,
String sslProtocol) {
try {
String trustStorePath = System
.getProperty("javax.net.ssl.trustStore");
// File keystoreFile = new File(trustStorePath);
// 由于android权限原因,无法读取trustStorePath="//system/etc/security/cacerts.bks"文件,此处由sdcard代替
File keystoreFile = new File("/sdcard/cacerts.bks");
InputStream in = new FileInputStream(keystoreFile);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passwd.toCharArray());
in.close();
SSLContext context = SSLContext.getInstance(sslProtocol);
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf
.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
javax.net.ssl.SSLSocketFactory factory = context.getSocketFactory();
boolean istrusted = false;
try {
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(50000);
socket.startHandshake();
socket.close();
istrusted = true;
} catch (SSLException e) {
Log.i("xx", e.getMessage());
istrusted = false;
}
if (!istrusted) {
X509Certificate[] chain = tm.chain;
if (chain == null) {
return;
}
ks.setCertificateEntry(host + "_" + 0, chain[0]);
// 如果想更改新密码,这个passwd替换成新密码即可
ks.store(new FileOutputStream(new File("/sdcard/cacerts.bks")),
passwd.toCharArray());
}
} catch (FileNotFoundException e) {
Log.e("xx", e.getMessage());
} catch (NoSuchAlgorithmException e) {
Log.e("xx", e.getMessage());
} catch (CertificateException e) {
Log.e("xx", e.getMessage());
} catch (IOException e) {
Log.e("xx", e.getMessage());
} catch (KeyStoreException e) {
Log.e("xx", e.getMessage());
} catch (KeyManagementException e) {
Log.e("xx", e.getMessage());
}
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}