Android实现https网络通信之添加指定信任证书/信任所有证书

Android客户端访问https网站,默认情况下,受证书信任限制,无法访问,可以有两种解决方法来实现:

1、将要访问的https网站的ca证书添加到客户端信任证书列表中,此种方式为谷歌推荐,安全性高。

2、将客户端设置为信任所有证书,也就是说不验证服务器证书,此种方式实现简单,但是安全性低,不推荐使用。

直接上代码,分别实现两种方式的访问。

1、客户端添加指定信任证书

assets目录中放置ca.crt证书,此证书为https://certs.cac.washington.edu/CAtest/网站的信任证书。


public void initSSL() throws CertificateException, IOException, KeyStoreException,
NoSuchAlgorithmException, KeyManagementException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream in = getAssets().open("ca.crt");
Certificate ca = cf.generateCertificate(in);

KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null, null);
keystore.setCertificateEntry("ca", ca);

String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keystore);

// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
URL url = new URL("https://certs.cac.washington.edu/CAtest/");
// URL url = new URL("https://github.com");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream input = urlConnection.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.e("TTTT", result.toString());
}

2、客户端信任所有https,免证书验证

public void initSSLALL() throws KeyManagementException, NoSuchAlgorithmException, IOException {
// URL url = new URL("https://certs.cac.washington.edu/CAtest/");
URL url = new URL("https://github.com");
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new TrustAllManager()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setRequestMethod("GET");
connection.connect();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = "";
StringBuffer result = new StringBuffer();
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.e("TTTT", result.toString());
}

参与评论