如何使用javax.net.ssl.SSLContext设置密码套件

时间:2018-12-28 02:39:48

标签: java-8 apache-httpclient-4.x sslcontext

在使用java8的Spring Boot应用程序中,我正在如下设置httpClient连接的基础SSLConext:

 import javax.net.ssl.SSLContext;

  SSLContext sslContext =  SSLContext.getInstance("TLSv1.2");
  sslContext.init(null, null, null); 

  CloseableHttpClient httpClient = HttpClientBuilder
          .create()
          .setConnectionManager(myConnectionManager)
          .setDefaultRequestConfig(rqConfig)
          .setSSLContext(sslContext)
          .build();

我需要将基础TLS1.2安全连接的密码套件设置为我选择的更强的名称。我没有在我的代码中创建sslContext的方式来实现此目的。

有人可以帮助我使用sslContext设置密码套件吗?

================更新================

 This is how I have now created my HttpClient

 CloseableHttpClient httpClient = HttpClientBuilder
          .create()
          .setConnectionManager(myConnectionManager)
          .setDefaultRequestConfig(rqConfig)
          .setSSLSocketFactory(new SSLConnectionSocketFactory(
                  SSLContexts.createSystemDefault(),
                  new String[]{"TLSv1.2"},
                  new String[] {"some-gibberish-cipher-suite"},
                  SSLConnectionSocketFactory.getDefaultHostnameVerifier()))
          .build();

1 个答案:

答案 0 :(得分:1)

创建自定义SSLConnectionSocketFactory实例时可以指定首选的TLS协议版本和自定义密码

CloseableHttpClient client = HttpClients.custom()
    .setSSLSocketFactory(new SSLConnectionSocketFactory(
            SSLContexts.createSystemDefault(),
            new String[]{"TLSv1.2"},
            new String[] {"TLS_RSA_WITH_AES_256_CBC_SHA256"},
            SSLConnectionSocketFactory.getDefaultHostnameVerifier()))
    .build();
try (CloseableHttpResponse response = client.execute(new HttpGet("https://httpbin.org/"))) {
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
}

或者,可以使用所需的SSL配置创建自定义PoolingHttpClientConnectionManager实例。

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
        .register("http", PlainConnectionSocketFactory.getSocketFactory())
        .register("https", new SSLConnectionSocketFactory(
                SSLContexts.createSystemDefault(),
                new String[]{"TLSv1.2"},
                new String[]{"TLS_RSA_WITH_AES_256_CBC_SHA256"},
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()))
        .build());

CloseableHttpClient client = HttpClients.custom()
    .setConnectionManager(cm)
    .build();
try (CloseableHttpResponse response = client.execute(new HttpGet("https://httpbin.org/"))) {
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
}