如何使⽤Java访问双向认证的Https资源本⽂的相关源码位于
0.Nginx配置Https双向认证
⾸先配置Https双向认证的服务器资源。
可以参考:
完成之后如下效果:
1.导⼊cacerts进⾏访问
⾸先将服务器证书导⼊keystore cacerts,默认密码为changeit,如果需要修改密码就改⼀下。
keytool -import -alias ssl.demo -keystore cacerts -file C:\Development\deployment\ssl\
需要使⽤管理员权限到你使⽤的JDK security⽬录下执⾏(注意如果你有多个JDK的情况),效果如下:
然后使⽤Java访问:
1package me.dreamingodd.ca;
2
3import org.apache.http.HttpEntity;
4import org.apache.hods.CloseableHttpResponse;
5import org.apache.hods.HttpGet;
6import org.ssl.SSLConnectionSocketFactory;
7import org.apache.http.impl.client.CloseableHttpClient;
8import org.apache.http.impl.client.HttpClients;
9import org.apache.http.ssl.SSLContexts;
10import org.apache.http.util.EntityUtils;
11
12import javax.ssl.SSLContext;
13import java.io.File;
14import java.io.FileInputStream;
15import java.io.InputStream;
16import java.security.KeyStore;
17
18
19/**
20 * #1
21 * HTTPS 双向认证 - direct into cacerts
22 * @Author Ye_Wenda
23 * @Date 7/11/2017
24*/
25public class HttpsKeyStoreDemo {
26// 客户端证书路径,⽤了本地绝对路径,需要修改
27private final static String PFX_PATH = "C:\\Development\\deployment\\ssl\\ca-demo\\client.p12";
28private final static String PFX_PWD = "demo"; //客户端证书密码及密钥库密码
29
30public static String sslRequestGet(String url) throws Exception {
31 KeyStore keyStore = Instance("PKCS12");
32 InputStream instream = new FileInputStream(new File(PFX_PATH));
33try {
34// 这⾥就指的是KeyStore库的密码
35 keyStore.load(instream, CharArray());
36 } finally {
37 instream.close();
38 }
39
40 SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, CharArray()).build();
41 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
42 , new String[] { "TLSv1" } // supportedProtocols ,这⾥可以按需要设置
43 , null// supportedCipherSuites
44 , DefaultHostnameVerifier());
45
46 CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
47try {
48 HttpGet httpget = new HttpGet(url);
49// httpost.addHeader("Connection", "keep-alive");// 设置⼀些heander等
50 CloseableHttpResponse response = ute(httpget);
51try {
52 HttpEntity entity = Entity();
53// 返回结果
54 String jsonStr = Entity(), "UTF-8");
55 sume(entity);
56return jsonStr;
57 } finally {
58 response.close();
59 }
60 } finally {
61 httpclient.close();
62 }
63 }
64
65public static void main(String[] args) throws Exception {
66 System.out.println(sslRequestGet("ssl.demo/"));
67 }
68
69 }
运⾏结果如下:
2.⽣成truststore库⽂件进⾏访问-原⽣⽅式
如果服务器的JDK/JRE不能随便改动,我们还可以使⽤⽣成truststore库的⽅式来实现。
⾸先通过ca.crt⽣成⾃⼰的truststore,把ca.crt复制⼀份,重命名为ca.cer,复制到security⽬录下,执⾏keytool -uststore -keypass demodemo -storepass demodemo -alias DemoCA -import -trustcacerts - 效果如下:
使⽤⽣成的uststore和client.p12进⾏java访问:
1package me.dreamingodd.ca;
2
3import javax.ssl.*;
4import java.io.*;
5import java.URL;
6import java.nio.charset.Charset;
7import java.security.KeyStore;
8
9
10/**
11 * #2
12 * HTTPS 双向认证 - use truststore
13 * 原⽣⽅式
14 * @Author Ye_Wenda
15 * @Date 7/11/2017
16*/
17public class HttpsTruststoreNativeDemo {
18// 客户端证书路径,⽤了本地绝对路径,需要修改
19private final static String CLIENT_CERT_FILE = "C:/Development/deployment/ssl/ca-demo/client.p12";
20// 客户端证书密码
21private final static String CLIENT_PWD = "demo";
22// 信任库路径
23private final static String TRUST_STRORE_FILE = "C:\\Development\\deployment\\ssl\\ca-demo\\uststore";
24// 信任库密码
25private final static String TRUST_STORE_PWD = "demodemo";
26
27
28private static String readResponseBody(InputStream inputStream) throws IOException {
29try {
30 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
31 StringBuffer sb = new StringBuffer();
32 String buff = null;
33while((buff = br.readLine()) != null){
34 sb.append(buff+"\n");
35 }
String();
37 } finally {
38 inputStream.close();
39 }
40 }
41
42public 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, CharArray());
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 = Instance("SSL");
57 ctx.KeyManagers(), trustManagerFactory
58 .getTrustManagers(), null);
59 SSLSocketFactory sf = SocketFactory();
60
61 HttpsURLConnection.setDefaultSSLSocketFactory(sf);
62 String url = "ssl.demo";
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 = InputStream());
70 System.out.println(response);
71 }
72
73/**
74 * 获得KeyStore
75 *
76 * @param keyStorePath
77 * @param password
78 * @return
79
80 * @throws Exception
81*/
82private static KeyStore getKeyStore(String keyStorePath, String password,String type)
83throws Exception {
84 FileInputStream is = new FileInputStream(keyStorePath);
85 KeyStore ks = Instance(type);
86 ks.load(is, CharArray());
87 is.close();
88return ks;
89 }
90
91
92public static void main(String[] args) throws Exception {
93 httpsCall();
94 }
95
96 }
结果同1。
3.⽣成truststore库⽂件进⾏访问-Apache HTTP 组件⽅式
package me.dreamingodd.ca;
import org.apache.hods.CloseableHttpResponse;
import org.apache.hods.HttpGet;
jdk怎么使用import org.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import javax.ssl.KeyManagerFactory;
import javax.ssl.SSLContext;
import javax.ssl.TrustManagerFactory;
import java.io.*;
import java.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\\uststore";
// 信任库密码
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");
}
String();
}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, CharArray());
// 初始化信任库
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 = Instance("SSL");
sslContext.KeyManagers(), TrustManagers(), new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,new String[]{"TLSv1", "TLSv2", "TLSv3"},null, DefaultHostnameVerifier());
CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLContext(sslContext).build();
HttpGet getCall = new HttpGet();
getCall.setURI(new URI("ssl.demo"));
CloseableHttpResponse response = ute(getCall);
System.out.println(Entity().getContent()));
}
public static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use adLine()
* 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 = adLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String();
}
/**
* 获得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 = Instance(type);
ks.load(is, CharArray());
is.close();
return ks;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论