Java中用HttpsURLConnection訪問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都必須做相同的操作;第二種方式靈活性更高,但是要小心實現,否則可能會留下安全隱患;