如何使用Java訪問雙向認證的Https資源

来源:http://www.cnblogs.com/dreamingodd/archive/2017/09/07/7491098.html
-Advertisement-
Play Games

本文藉鑒了同事 JayChang的研究成果,這裡是他的博客:http://jaychang.cn/ http://jaychang.iteye.com/category/105859 ...


本文的相關源碼位於 https://github.com/dreamingodd/CA-generation-demo 

 

0.Nginx配置Https雙向認證

首先配置Https雙向認證的伺服器資源。

可以參考:http://www.cnblogs.com/dreamingodd/p/7357029.html

完成之後如下效果:

 

1.導入cacerts進行訪問

首先將伺服器證書導入keystore cacerts,預設密碼為changeit,如果需要修改密碼就改一下。

keytool -import -alias ssl.demo.com -keystore cacerts -file C:\Development\deployment\ssl\ca-demo\server.crt

需要使用管理員許可權到你使用的JDK security目錄下執行(註意如果你有多個JDK的情況),效果如下:

然後使用Java訪問:

 1 package me.dreamingodd.ca;
 2 
 3 import org.apache.http.HttpEntity;
 4 import org.apache.http.client.methods.CloseableHttpResponse;
 5 import org.apache.http.client.methods.HttpGet;
 6 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
 7 import org.apache.http.impl.client.CloseableHttpClient;
 8 import org.apache.http.impl.client.HttpClients;
 9 import org.apache.http.ssl.SSLContexts;
10 import org.apache.http.util.EntityUtils;
11 
12 import javax.net.ssl.SSLContext;
13 import java.io.File;
14 import java.io.FileInputStream;
15 import java.io.InputStream;
16 import java.security.KeyStore;
17 
18 
19 /**
20  * #1
21  * HTTPS 雙向認證 - direct into cacerts
22  * @Author Ye_Wenda
23  * @Date 7/11/2017
24  */
25 public class HttpsKeyStoreDemo {
26     // 客戶端證書路徑,用了本地絕對路徑,需要修改
27     private final static String PFX_PATH = "C:\\Development\\deployment\\ssl\\ca-demo\\client.p12";
28     private final static String PFX_PWD = "demo"; //客戶端證書密碼及密鑰庫密碼
29 
30     public static String sslRequestGet(String url) throws Exception {
31         KeyStore keyStore = KeyStore.getInstance("PKCS12");
32         InputStream instream = new FileInputStream(new File(PFX_PATH));
33         try {
34             // 這裡就指的是KeyStore庫的密碼
35             keyStore.load(instream, PFX_PWD.toCharArray());
36         } finally {
37             instream.close();
38         }
39 
40         SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PFX_PWD.toCharArray()).build();
41         SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
42                 , new String[] { "TLSv1" }  // supportedProtocols ,這裡可以按需要設置
43                 , null  // supportedCipherSuites
44                 , SSLConnectionSocketFactory.getDefaultHostnameVerifier());
45 
46         CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
47         try {
48             HttpGet httpget = new HttpGet(url);
49 //          httpost.addHeader("Connection", "keep-alive");// 設置一些heander等
50             CloseableHttpResponse response = httpclient.execute(httpget);
51             try {
52                 HttpEntity entity = response.getEntity();
53                 // 返回結果
54                 String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
55                 EntityUtils.consume(entity);
56                 return jsonStr;
57             } finally {
58                 response.close();
59             }
60         } finally {
61             httpclient.close();
62         }
63     }
64 
65     public static void main(String[] args) throws Exception {
66         System.out.println(sslRequestGet("https://ssl.demo.com/"));
67     }
68 
69 }

運行結果如下:

 

2.生成truststore庫文件進行訪問-原生方式

如果伺服器的JDK/JRE不能隨便改動,我們還可以使用生成truststore庫的方式來實現。

首先通過ca.crt生成自己的truststore,把ca.crt複製一份,重命名為ca.cer,複製到security目錄下,執行

keytool -keystore demo.truststore -keypass demodemo -storepass demodemo -alias DemoCA -import -trustcacerts -file ca.cer

效果如下:

使用生成的demo.truststore和client.p12進行java訪問:

 1 package me.dreamingodd.ca;
 2 
 3 import javax.net.ssl.*;
 4 import java.io.*;
 5 import java.net.URL;
 6 import java.nio.charset.Charset;
 7 import java.security.KeyStore;
 8 
 9 
10 /**
11  * #2
12  * HTTPS 雙向認證 - use truststore
13  * 原生方式
14  * @Author Ye_Wenda
15  * @Date 7/11/2017
16  */
17 public class HttpsTruststoreNativeDemo {
18     // 客戶端證書路徑,用了本地絕對路徑,需要修改
19     private final static String CLIENT_CERT_FILE = "C:/Development/deployment/ssl/ca-demo/client.p12";
20     // 客戶端證書密碼
21     private final static String CLIENT_PWD = "demo";
22     // 信任庫路徑
23     private final static String TRUST_STRORE_FILE = "C:\\Development\\deployment\\ssl\\ca-demo\\demo.truststore";
24     // 信任庫密碼
25     private final static String TRUST_STORE_PWD = "demodemo";
26 
27 
28     private static String readResponseBody(InputStream inputStream) throws IOException {
29         try {
30             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
31             StringBuffer sb = new StringBuffer();
32             String buff = null;
33             while((buff = br.readLine()) != null){
34                 sb.append(buff+"\n");
35             }
36             return sb.toString();
37         } finally {
38             inputStream.close();
39         }
40     }
41 
42     public static void httpsCall() throws Exception {
43         // 初始化密鑰庫
44         KeyManagerFactory keyManagerFactory = KeyManagerFactory
45                 .getInstance("SunX509");
46         KeyStore keyStore = getKeyStore(CLIENT_CERT_FILE, CLIENT_PWD, "PKCS12");
47         keyManagerFactory.init(keyStore, CLIENT_PWD.toCharArray());
48 
49         // 初始化信任庫
50         TrustManagerFactory trustManagerFactory = TrustManagerFactory
51                 .getInstance("SunX509");
52         KeyStore trustkeyStore = getKeyStore(TRUST_STRORE_FILE, TRUST_STORE_PWD,"JKS");
53         trustManagerFactory.init(trustkeyStore);
54 
55         // 初始化SSL上下文
56         SSLContext ctx = SSLContext.getInstance("SSL");
57         ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory
58                 .getTrustManagers(), null);
59         SSLSocketFactory sf = ctx.getSocketFactory();
60 
61         HttpsURLConnection.setDefaultSSLSocketFactory(sf);
62         String url = "https://ssl.demo.com";
63         URL urlObj = new URL(url);
64         HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
65         con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
66         con.setRequestProperty("Accept-Language", "zh-CN;en-US,en;q=0.5");
67         con.setRequestMethod("GET");
68 
69         String response = readResponseBody(con.getInputStream());
70         System.out.println(response);
71     }
72 
73     /**
74      * 獲得KeyStore
75      *
76      * @param keyStorePath
77      * @param password
78      * @return
79 
80      * @throws Exception
81      */
82     private static KeyStore getKeyStore(String keyStorePath, String password,String type)
83             throws Exception {
84         FileInputStream is = new FileInputStream(keyStorePath);
85         KeyStore ks = KeyStore.getInstance(type);
86         ks.load(is, password.toCharArray());
87         is.close();
88         return ks;
89     }
90 
91 
92     public static void main(String[] args) throws Exception {
93         httpsCall();
94     }
95 
96 }

 

結果同1。

 

3.生成truststore庫文件進行訪問-Apache HTTP 組件方式

 

package me.dreamingodd.ca;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.SecureRandom;

/**
 * #3
 * HTTPS 雙向認證 - use truststore
 * Apache插件
 * @Author Ye_Wenda
 * @Date 7/11/2017
 */
public class HttpsTruststoreApacheContextDemo {
    // 客戶端證書路徑,用了本地絕對路徑,需要修改
    private final static String CLIENT_CERT_FILE = "C:/Development/deployment/ssl/ca-demo/client.p12";
    // 客戶端證書密碼
    private final static String CLIENT_PWD = "demo";
    // 信任庫路徑
    private final static String TRUST_STRORE_FILE = "C:\\Development\\deployment\\ssl\\ca-demo\\demo.truststore";
    // 信任庫密碼
    private final static String TRUST_STORE_PWD = "demodemo";


    private static String readResponseBody(InputStream inputStream) throws IOException {
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            StringBuffer sb = new StringBuffer();
            String buff = null;
            while((buff = br.readLine()) != null){
                sb.append(buff+"\n");
            }
            return sb.toString();
        }finally{
            inputStream.close();
        }
    }

    public static void httpsCall() throws Exception {
        // 初始化密鑰庫
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance("SunX509");
        KeyStore keyStore = getKeyStore(CLIENT_CERT_FILE, CLIENT_PWD, "PKCS12");
        keyManagerFactory.init(keyStore, CLIENT_PWD.toCharArray());

        // 初始化信任庫
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance("SunX509");
        KeyStore trustkeyStore = getKeyStore(TRUST_STRORE_FILE, TRUST_STORE_PWD,"JKS");
        trustManagerFactory.init(trustkeyStore);

//        SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, "123456".toCharArray())
//            .loadTrustMaterial(new File(TRUST_STRORE_FILE),"012345".toCharArray()).setSecureRandom(new SecureRandom()).useProtocol("SSL").build();
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());

        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,new String[]{"TLSv1", "TLSv2", "TLSv3"},null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

        CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLContext(sslContext).build();
        HttpGet getCall = new HttpGet();
        getCall.setURI(new URI("https://ssl.demo.com"));
        CloseableHttpResponse response = closeableHttpClient.execute(getCall);
        System.out.println(convertStreamToString(response.getEntity().getContent()));

    }

    public static String convertStreamToString(InputStream is) {
        /*
          * To convert the InputStream to String we use the BufferedReader.readLine()
          * method. We iterate until the BufferedReader return null which means
          * there's no more data to read. Each line will appended to a StringBuilder
          * and returned as String.
          */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    /**
     * 獲得KeyStore
     *
     * @param keyStorePath
     * @param password
     * @return
     * @throws Exception
     */
    private static KeyStore getKeyStore(String keyStorePath, String password,String type)
            throws Exception {
        FileInputStream is = new FileInputStream(keyStorePath);
        KeyStore ks = KeyStore.getInstance(type);
        ks.load(is, password.toCharArray());
        is.close();
        return ks;
    }



    public static void main(String[] args) throws Exception {
        httpsCall();
    }
}

 

結果同2。

 

本文的相關源碼位於 https://github.com/dreamingodd/CA-generation-demo 

 

dreamingodd原創文章,如轉載請註明出處。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在日常工作中,在編輯文檔時,為了方便自己或者Boss能夠實時查看到需要的網頁或者文檔是,需要對在Excel中輸入的相關文字進行超鏈接,那麼對於一些在Excel中插入的圖片我們該怎麼實現超鏈接呢,下麵給大家分享一個方法: 首先簡單瞭解一下一款叫Spire.XLS的組件,這個組件是由E-iceblue公 ...
  • 前幾天看到一篇博文:C# 爬蟲 抓取小說 博主使用的是正則表達式獲取小說的名字、目錄以及內容。 下麵使用HtmlAgilityPack來改寫原博主的代碼 在使用HtmlAgilityPack之前,可以先熟悉一下XPath:點我 代碼如下: 1 using System; 2 using System ...
  • 為什麼你什麼都沒乾,但QQ空間中卻發了很多小廣告?也許你的QQ賬號已經被盜。本文將講解一個QQ的快速登錄的漏洞。 我前陣子在論壇上看到一個QQ的快速登錄的漏洞,覺得非常不錯,所以把部分原文給轉到園子來。 而利用這個漏洞最終可以實現,只要你點擊一個頁面或運行過一個程式,那麼我就可以擁有你的登錄許可權。可 ...
  • 最近在學習.NET CORE ,剛開始就遇到問題了。 安裝EF框架的試試就報錯, 報錯如下: 錯誤 程式包還原失敗。正在回滾“XXX”的程式包更改。 找了好久的方案,網上也沒搜到對應的問題和方案,然而我看到輸出中一閃而過的信息,我就截圖看到了信息,然後仔細看了下,就發現是版本號不一致。 解決方案:1 ...
  • 走過的彎路: 1. DoWork方法中不能操縱UI控制項。 2. DoWork事件中調用ReportProgress方法,在ProgressChanged事件中可以操縱UI控制項。 3. WorkerReportsProgress屬性必須設置true. (預設是false. 因為這塊,費了不少時間找原因 ...
  • 【才疏學淺,難免有紕漏,若有不正確的地方,歡迎指教】 MFC中有一個庫函數 Tokenize(); 函數原型:CStringT Tokenize( PCXSTR pszTokens , int& iStart ) const; 這個函數可以根據某個字元將CString分隔開。 事先設定好緩衝區,被分 ...
  • SOAP 簡單對象訪問協議, webService三要素 , SOAP、WSDL(WebServicesDescriptionLanguage)、UDDI(UniversalDescriptionDiscovery andIntegration)之一, soap用來描述傳遞信息的格式, WSDL 用 ...
  • 錯誤原因:Mapper對應的XXXMapper.xml中的\標簽的resultType和resultMap搞混了,resultType需要對應一個類,而resultMap對應\標簽中定義的映射。關於兩者的區別可見:http://blog.csdn.net/woshixuye/article/deta ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...