Java中用HttpsURLConnection訪問Https連結的問題

來源:互聯網
上載者:User

在web應用互動過程中,有很多情境需要保證通訊資料的安全;在前面也有好多篇文章介紹了在Web Service調用過程中用WS-Security來保證介面互動過程的安全性,值得注意的是,該種方式基於的傳輸協議仍然是Http,採用這種方式可擴充性和資料互動效率比較高;另外一種實現方式就是用Https,他是在協議層對Http的再次封裝,加入了SSL/TLS,採用該協議進行通訊的資料全部都會被加密,由於目前Web開發編程中對此都有了一定程度的封裝,所以採用Https對外提供服務,除了認證以外,對編程能力的要求並不高,相對於前者門檻較低,但是由於對雙方通訊的所有資料都進行加密,而且互動過程中還有多次握手等,所以效率較低;以下就介紹下在Java中訪問Https連結時會出現的一些問題;

在Java中要訪問Https連結時,會用到一個關鍵類HttpsURLConnection;參見如下實現代碼:

  1.         // 建立URL對象
  2.         URL myURL = new URL("https://www.sun.com");
  3.         // 建立HttpsURLConnection對象,並設定其SSLSocketFactory對象
  4.         HttpsURLConnection httpsConn = (HttpsURLConnection) myURL
  5.                 .openConnection();
  6.         // 取得該串連的輸入資料流,以讀取響應內容
  7.         InputStreamReader insr = new InputStreamReader(httpsConn
  8.                 .getInputStream());
  9.         // 讀取伺服器的響應內容並顯示
  10.         int respInt = insr.read();
  11.         while (respInt != -1) {
  12.             System.out.print((char) respInt);
  13.             respInt = insr.read();
  14.         }

在取得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時的代碼:

  1. package test;
  2. import java.io.FileInputStream;
  3. import java.security.KeyStore;
  4. import java.security.cert.CertificateException;
  5. import java.security.cert.X509Certificate;
  6. import javax.net.ssl.TrustManager;
  7. import javax.net.ssl.TrustManagerFactory;
  8. import javax.net.ssl.X509TrustManager;
  9. public class MyX509TrustManager implements X509TrustManager {
  10.     /*
  11.      * The default X509TrustManager returned by SunX509.  We'll delegate
  12.      * decisions to it, and fall back to the logic in this class if the
  13.      * default X509TrustManager doesn't trust it.
  14.      */
  15.     X509TrustManager sunJSSEX509TrustManager;
  16.     MyX509TrustManager() throws Exception {
  17.         // create a "default" JSSE X509TrustManager.
  18.         KeyStore ks = KeyStore.getInstance("JKS");
  19.         ks.load(new FileInputStream("trustedCerts"),
  20.             "passphrase".toCharArray());
  21.         TrustManagerFactory tmf =
  22.         TrustManagerFactory.getInstance("SunX509", "SunJSSE");
  23.         tmf.init(ks);
  24.         TrustManager tms [] = tmf.getTrustManagers();
  25.         /*
  26.          * Iterate over the returned trustmanagers, look
  27.          * for an instance of X509TrustManager.  If found,
  28.          * use that as our "default" trust manager.
  29.          */
  30.         for (int i = 0; i < tms.length; i++) {
  31.             if (tms[i] instanceof X509TrustManager) {
  32.                 sunJSSEX509TrustManager = (X509TrustManager) tms[i];
  33.                 return;
  34.             }
  35.         }
  36.         /*
  37.          * Find some other way to initialize, or else we have to fail the
  38.          * constructor.
  39.          */
  40.         throw new Exception("Couldn't initialize");
  41.     }
  42.     /*
  43.      * Delegate to the default trust manager.
  44.      */
  45.     public void checkClientTrusted(X509Certificate[] chain, String authType)
  46.                 throws CertificateException {
  47.         try {
  48.             sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
  49.         } catch (CertificateException excep) {
  50.             // do any special handling here, or rethrow exception.
  51.         }
  52.     }
  53.     /*
  54.      * Delegate to the default trust manager.
  55.      */
  56.     public void checkServerTrusted(X509Certificate[] chain, String authType)
  57.                 throws CertificateException {
  58.         try {
  59.             sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
  60.         } catch (CertificateException excep) {
  61.             /*
  62.              * Possibly pop up a dialog box asking whether to trust the
  63.              * cert chain.
  64.              */
  65.         }
  66.     }
  67.     /*
  68.      * Merely pass this through.
  69.      */
  70.     public X509Certificate[] getAcceptedIssuers() {
  71.         return sunJSSEX509TrustManager.getAcceptedIssuers();
  72.     }
  73. }

  1.         // 建立SSLContext對象,並使用我們指定的信任管理器初始化
  2.         TrustManager[] tm = { new MyX509TrustManager() };
  3.         SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
  4.         sslContext.init(null, tm, new java.security.SecureRandom());
  5.         // 從上述SSLContext對象中得到SSLSocketFactory對象
  6.         SSLSocketFactory ssf = sslContext.getSocketFactory();
  7.         // 建立URL對象
  8.         URL myURL = new URL("https://ebanks.gdb.com.cn/sperbank/perbankLogin.jsp");
  9.         // 建立HttpsURLConnection對象,並設定其SSLSocketFactory對象
  10.         HttpsURLConnection httpsConn = (HttpsURLConnection) myURL.openConnection();
  11.         httpsConn.setSSLSocketFactory(ssf);
  12.         // 取得該串連的輸入資料流,以讀取響應內容
  13.         InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());
  14.         // 讀取伺服器的響應內容並顯示
  15.         int respInt = insr.read();
  16.         while (respInt != -1) {
  17.             System.out.print((char) respInt);
  18.             respInt = insr.read();
  19.         }

對於以上兩種實現方式,各有各的優點,第一種方式不會破壞JSSE的安全性,但是要手工匯入認證,如果伺服器很多,那每台伺服器的JRE都必須做相同的操作;第二種方式靈活性更高,但是要小心實現,否則可能會留下安全隱患;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.