上篇文章有寫如何在Android上開啟https單向認證的方法,說白了單向認證的過程就是用戶端認證伺服器的身份。下面我們來讨論伺服器端如何認證用戶端的身份。
網上很多人都說Android隻認識BKS格式的證書,但是查了官方文檔以後可以看到
是以,我這裡采用PKCS12格式的證書,
由于我的整個系統都需要使用該證書,是以我需要将它導入到系統中,在這裡我使用了一種比較取巧的方式
void initSSL() {
try{
InputStream kmin = this.getApplicationContext().getAssets().open("leikey1.p12");
KeyStore kmkeyStore = KeyStore.getInstance("PKCS12");
kmkeyStore.load(kmin,strKeyPWD.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(kmkeyStore, strKeyPWD.toCharArray());
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
SSLContext.setDefault(context);
Log.d(TAG, "init SSLContext for Https!");
}catch(Exception e){
e.printStackTrace();
}
}
使用方式如下:
void testConnect() {
try{
URL url = new URL(strUrl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
//主要是添加這行代碼,我們的公鑰和私鑰都存在系統裡面,通過下面這行代碼調用。
urlConnection.setSSLSocketFactory(SSLContext.getDefault().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(TAG, result.toString());
}catch(Exception e){
e.printStackTrace();
}
}
參考文檔
https://developer.android.google.cn/reference/java/security/KeyStore.html
http://frank-zhu.github.io/android/2014/12/26/android-https-ssl/
http://blog.csdn.net/zww986736788/article/details/78425459
http://blog.csdn.net/Innost/article/details/44081147
http://blog.csdn.net/Innost/article/details/44199503