使用HttpsURLConnection訪問HTTPS連結時一般需要引入證照,否則會產生異常。
但是也可以使用信任所有證照的方式來達到訪問的目的。
經上網查詢資料發現一個很好用的類來實現信任所有證照的功能。特此記錄。
程式碼來自[這裡](http://javaweb.org/?p=1237)
類程式碼
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class SslUtils {
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager, X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
return;
}
}
/**
* 忽略HTTPS請求的SSL證照,必須在openConnection之前呼叫
*
* @throws Exception
*/
public static void ignoreSsl() throws Exception {
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
}
呼叫方式
在openConnection之前呼叫SslUtils.ignoreSsl();即可忽略所有HTTPS連結的證照。
在web應用互動過程中,有很多場景需要保證通訊資料的安全;在前面也有好多篇文章介紹了在Web Service呼叫過程中用WS-Security來保證介面互動過程的安全性,值得注意的是,該種方式基於的傳輸協議仍然是Http,採用這種方式可擴充套件性和資料互動效率比較高;另外一種實現方式就是用Https,他是在協議層對Http的再次封裝,加入了SSL/TLS,採用該協議進行通訊的資料全部都會被加密,由於目前Web開發程式設計中對此都有了一定程度的封裝,所以採用Https對外提供服務,除了證照以外,對程式設計能力的要求並不高,相對於前者門檻較低,但是由於對雙方通訊的所有資料都進行加密,而且互動過程中還有多次握手等,所以效率較低;以下就介紹下在Java中訪問Https連結時會出現的一些問題;
在Java中要訪問Https連結時,會用到一個關鍵類HttpsURLConnection;參見如下實現程式碼:
- // 建立URL物件
- URL myURL = new URL(“https://www.sun.com”);
- // 建立HttpsURLConnection物件,並設定其SSLSocketFactory物件
- HttpsURLConnection httpsConn = (HttpsURLConnection) myURL
- .openConnection();
- // 取得該連線的輸入流,以讀取響應內容
- InputStreamReader insr = new InputStreamReader(httpsConn
- .getInputStream());
- // 讀取伺服器的響應內容並顯示
- int respInt = insr.read();
- while (respInt != –1) {
- System.out.print((char) respInt);
- respInt = insr.read();
- }
在取得connection的時候和正常瀏覽器訪問一樣,仍然會驗證服務端的證照是否被信任(權威機構發行或者被權威機構簽名);如果服務端證照不被信任,則預設的實現就會有問題,一般來說,用SunJSSE會拋如下異常資訊:
javax.NET.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
上面提到SunJSSE,JSSE(Java Secure Socket Extension)是實現Internet安全通訊的一系列包的集合。它是一個SSL和TLS的純Java實現,可以透明地提供資料加密、伺服器認證、資訊完整性等功能,可以使我們像使用普通的套接字一樣使用JSSE建立的安全套接字。JSSE是一個開放的標準,不只是Sun公司才能實現一個SunJSSE,事實上其他公司有自己實現的JSSE,然後通過JCA就可以在JVM中使用。
關於JSSE的詳細資訊參考官網Reference:http://java.sun.com/j2se/1.5.0/docs/guide/security/jsse/JSSERefGuide.html;
以及java Security Guide:http://java.sun.com/j2se/1.5.0/docs/guide/security/;
在深入瞭解JSSE之前,需要了解一個有關Java安全的概念:客戶端的TrustStore檔案。客戶端的TrustStore檔案中儲存著被客戶端所信任的伺服器的證照資訊。客戶端在進行SSL連線時,JSSE將根據這個檔案中的證照決定是否信任伺服器端的證照。在SunJSSE中,有一個信任管理器類負責決定是否信任遠端的證照,這個類有如下的處理規則:
1、若系統屬性javax.net.sll.trustStore指定了TrustStore檔案,那麼信任管理器就去jre安裝路徑下的lib/security/目錄中尋找並使用這個檔案來檢查證照。
2、若該系統屬性沒有指定TrustStore檔案,它就會去jre安裝路徑下尋找預設的TrustStore檔案,這個檔案的相對路徑為:lib/security/jssecacerts。
3、若jssecacerts不存在,但是cacerts存在(它隨J2SDK一起發行,含有數量有限的可信任的基本證照),那麼這個預設的TrustStore檔案就是lib/security/cacerts。
那遇到這種情況,怎麼處理呢?有以下兩種方案:
1、按照以上信任管理器的規則,將服務端的公鑰匯入到jssecacerts,或者是在系統屬性中設定要載入的trustStore檔案的路徑;證照匯入可以用如下命令:keytool -import -file src_cer_file –keystore dest_cer_store;至於證照可以通過瀏覽器匯出獲得;
2、實現自己的證照信任管理器類,比如MyX509TrustManager,該類必須實現X509TrustManager介面中的三個method;然後在HttpsURLConnection中載入自定義的類,可以參見如下兩個程式碼片段,其一為自定義證照信任管理器,其二為connect時的程式碼:
- package test;
- import java.io.FileInputStream;
- import java.security.KeyStore;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- import javax.net.ssl.TrustManager;
- import javax.net.ssl.TrustManagerFactory;
- import javax.net.ssl.X509TrustManager;
- public class MyX509TrustManager implements X509TrustManager {
- /*
- * The default X509TrustManager returned by SunX509. We`ll delegate
- * decisions to it, and fall back to the logic in this class if the
- * default X509TrustManager doesn`t trust it.
- */
- X509TrustManager sunJSSEX509TrustManager;
- MyX509TrustManager() throws Exception {
- // create a “default” JSSE X509TrustManager.
- KeyStore ks = KeyStore.getInstance(“JKS”);
- ks.load(new FileInputStream(“trustedCerts”),
- “passphrase”.toCharArray());
- TrustManagerFactory tmf =
- TrustManagerFactory.getInstance(“SunX509”, “SunJSSE”);
- tmf.init(ks);
- TrustManager tms [] = tmf.getTrustManagers();
- /*
- * Iterate over the returned trustmanagers, look
- * for an instance of X509TrustManager. If found,
- * use that as our “default” trust manager.
- */
- for (int i = 0; i < tms.length; i++) {
- if (tms[i] instanceof X509TrustManager) {
- sunJSSEX509TrustManager = (X509TrustManager) tms[i];
- return;
- }
- }
- /*
- * Find some other way to initialize, or else we have to fail the
- * constructor.
- */
- throw new Exception(“Couldn`t initialize”);
- }
- /*
- * Delegate to the default trust manager.
- */
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- try {
- sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
- } catch (CertificateException excep) {
- // do any special handling here, or rethrow exception.
- }
- }
- /*
- * Delegate to the default trust manager.
- */
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- try {
- sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
- } catch (CertificateException excep) {
- /*
- * Possibly pop up a dialog box asking whether to trust the
- * cert chain.
- */
- }
- }
- /*
- * Merely pass this through.
- */
- public X509Certificate[] getAcceptedIssuers() {
- return sunJSSEX509TrustManager.getAcceptedIssuers();
- }
- }
- // 建立SSLContext物件,並使用我們指定的信任管理器初始化
- TrustManager[] tm = { new MyX509TrustManager() };
- SSLContext sslContext = SSLContext.getInstance(“SSL”, “SunJSSE”);
- sslContext.init(null, tm, new java.security.SecureRandom());
- // 從上述SSLContext物件中得到SSLSocketFactory物件
- SSLSocketFactory ssf = sslContext.getSocketFactory();
- // 建立URL物件
- URL myURL = new URL(“https://ebanks.gdb.com.cn/sperbank/perbankLogin.jsp”);
- // 建立HttpsURLConnection物件,並設定其SSLSocketFactory物件
- HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
- httpsConn.setSSLSocketFactory(ssf);
- // 取得該連線的輸入流,以讀取響應內容
- InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());
- // 讀取伺服器的響應內容並顯示
- int respInt = insr.read();
- while (respInt != –1) {
- System.out.print((char) respInt);
- respInt = insr.read();
- }
對於以上兩種實現方式,各有各的優點,第一種方式不會破壞JSSE的安全性,但是要手工匯入證照,如果伺服器很多,那每臺伺服器的JRE都必須做相同的操作;第二種方式靈活性更高,但是要小心實現,否則可能會留下安全隱患;