【发布时间】:2018-07-05 00:33:47
【问题描述】:
这里有一个自定义 SSL 的示例:
https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java
/**
* This example demonstrates how to create secure connections with a custom SSL
* context.
*/
public class ClientCustomSSL {
public final static void main(String[] args) throws Exception {
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),
new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://httpbin.org/");
System.out.println("Executing request " + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
为什么我们需要它?我已经测试了一个没有任何 SSL 内容的 HttpClient 请求,并且我从 HTTPS url 获得了正确的响应而没有错误。
如果我不添加任何 SSLContext 会有什么问题?
如果让它更安全很重要,这条线是什么?:
.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),
看来我们需要一些文件和一些密码?
【问题讨论】:
-
该示例使用密钥库,这意味着它正在执行客户端身份验证。显然,要么您的服务器没有请求客户端证书,要么不介意您没有发送证书,因为您没有配置密钥库。
-
@EJP:代码使用了一个 named 密钥库,并且显然是密钥库格式(因为它是这样读取的,不会引发异常),但它使用内容作为信任材料,即作为信任库,以验证服务器。对于 Apache httpclient 进行客户端身份验证,您调用(其中一个重载)
SSLContextBuilder.loadKeyMaterial
标签: java apache-httpclient-4.x