HTTPS 信任證書

  1. 使用HttpsURLConnection訪問HTTPS連接時通常須要引入證書,不然會產生異常。
  2. 可是也可使用信任全部證書的方式來達到訪問的目的。
  3. 經上網查詢資料發現一個很好用的類來實現信任全部證書的功能。特此記錄。
  4. 代碼來自[這裏](http://javaweb.org/?p=1237)

類代碼

  1. import java.security.cert.CertificateException;
  2. import java.security.cert.X509Certificate;
  3. import javax.net.ssl.HostnameVerifier;
  4. import javax.net.ssl.HttpsURLConnection;
  5. import javax.net.ssl.SSLContext;
  6. import javax.net.ssl.SSLSession;
  7. import javax.net.ssl.TrustManager;
  8. import javax.net.ssl.X509TrustManager;
  9. public class SslUtils {
  10. private static void trustAllHttpsCertificates() throws Exception {
  11. TrustManager[] trustAllCerts = new TrustManager[1];
  12. TrustManager tm = new miTM();
  13. trustAllCerts[0] = tm;
  14. SSLContext sc = SSLContext.getInstance("SSL");
  15. sc.init(null, trustAllCerts, null);
  16. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  17. }
  18. static class miTM implements TrustManager, X509TrustManager {
  19. public X509Certificate[] getAcceptedIssuers() {
  20. return null;
  21. }
  22. public boolean isServerTrusted(X509Certificate[] certs) {
  23. return true;
  24. }
  25. public boolean isClientTrusted(X509Certificate[] certs) {
  26. return true;
  27. }
  28. public void checkServerTrusted(X509Certificate[] certs, String authType)
  29. throws CertificateException {
  30. return;
  31. }
  32. public void checkClientTrusted(X509Certificate[] certs, String authType)
  33. throws CertificateException {
  34. return;
  35. }
  36. }
  37. /**
  38. * 忽略HTTPS請求的SSL證書,必須在openConnection以前調用
  39. *
  40. * @throws Exception
  41. */
  42. public static void ignoreSsl() throws Exception {
  43. HostnameVerifier hv = new HostnameVerifier() {
  44. public boolean verify(String urlHostName, SSLSession session) {
  45. System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
  46. return true;
  47. }
  48. };
  49. trustAllHttpsCertificates();
  50. HttpsURLConnection.setDefaultHostnameVerifier(hv);
  51. }
  52. }

調用方式

  1. openConnection以前調用SslUtils.ignoreSsl();便可忽略全部HTTPS連接的證書。

 


 

 

 

 

 

 

在web應用交互過程當中,有不少場景須要保證通訊數據的安全;在前面也有好多篇文章介紹了在Web Service調用過程當中用WS-Security來保證接口交互過程的安全性,值得注意的是,該種方式基於的傳輸協議仍然是Http,採用這種方式可擴展性和數據交互效率比較高;另一種實現方式就是用Https,他是在協議層對Http的再次封裝,加入了SSL/TLS,採用該協議進行通訊的數據所有都會被加密,因爲目前Web開發編程中對此都有了必定程度的封裝,因此採用Https對外提供服務,除了證書之外,對編程能力的要求並不高,相對於前者門檻較低,可是因爲對雙方通訊的全部數據都進行加密,並且交互過程當中還有屢次握手等,因此效率較低;如下就介紹下在Java中訪問Https連接時會出現的一些問題;html

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

  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 targetweb

上面提到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中,有一個信任管理器類負責決定是否信任遠端的證書,這個類有以下的處理規則:
一、若系統屬性javax.net.sll.trustStore指定了TrustStore文件,那麼信任管理器就去jre安裝路徑下的lib/security/目錄中尋找並使用這個文件來檢查證書。
二、若該系統屬性沒有指定TrustStore文件,它就會去jre安裝路徑下尋找默認的TrustStore文件,這個文件的相對路徑爲:lib/security/jssecacerts
三、若jssecacerts不存在,可是cacerts存在(它隨J2SDK一塊兒發行,含有數量有限的可信任的基本證書),那麼這個默認的TrustStore文件就是lib/security/cacerts瀏覽器

那遇到這種狀況,怎麼處理呢?有如下兩種方案:
一、按照以上信任管理器的規則,將服務端的公鑰導入到jssecacerts,或者是在系統屬性中設置要加載的trustStore文件的路徑;證書導入能夠用以下命令:keytool -import -file src_cer_file –keystore dest_cer_store;至於證書能夠經過瀏覽器導出得到;
二、實現本身的證書信任管理器類,好比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都必須作相同的操做;第二種方式靈活性更高,可是要當心實現,不然可能會留下安全隱患;服務器

相關文章
相關標籤/搜索