Java Code Examples for org.apache.http.ssl.SSLContexts#custom()

The following examples show how to use org.apache.http.ssl.SSLContexts#custom() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 7 votes vote down vote up
protected SSLContext generateSSLContext() {
    SSLContextBuilder contextBuilder = SSLContexts.custom();
    try {
        if (getTrustStoreFile() != null) {
            contextBuilder.loadTrustMaterial(getTrustStoreFile(), getTrustStorePassword(), getTrustStrategy());
        }

        if (getKeyStoreFile() != null) {
            contextBuilder.loadKeyMaterial(getKeyStoreFile(), getKeyStorePassword(), getKeyPassword(), getPrivateKeyStrategy());
        }

        return contextBuilder.build();
    } catch (GeneralSecurityException | IOException e) {
        throw new RuntimeException("Unable to configure SSL", e);
    }
}
 
Example 2
Source File: SettingsBasedSSLConfigurator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
SSLContext buildSSLContext() throws SSLConfigException {
    try {
        if (isTrustAllEnabled()) {
            sslContextBuilder = new OverlyTrustfulSSLContextBuilder();
        } else {
            sslContextBuilder = SSLContexts.custom();
        }

        configureWithSettings();

        if (!this.enabled) {
            return null;
        }

        return sslContextBuilder.build();

    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new SSLConfigException("Error while initializing SSL configuration for " + this.clientName, e);
    }
}
 
Example 3
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private synchronized SSLContext createSecureSslContext() {
    if (secureSslContext == null) {
        log.debug("Protocol: {}", config.getProtocol());
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        try {
            loadTrustMaterial(sslContextBuilder);
            loadKeyMaterial(sslContextBuilder);
            secureSslContext = sslContextBuilder.build();
            validateSslConfig();
            return secureSslContext;
        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
                | UnrecoverableKeyException | KeyManagementException e) {
            apimlLog.log("org.zowe.apiml.common.sslContextInitializationError", e.getMessage());
            throw new HttpsConfigError("Error initializing SSL Context: " + e.getMessage(), e,
                    ErrorCode.HTTP_CLIENT_INITIALIZATION_FAILED, config);
        }
    } else {
        return secureSslContext;
    }
}
 
Example 4
Source File: DefaultConsulConfigGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory createFactoryFromAgentConfig(ConsulConfig.AgentConfig agentConfig) {
    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        if (agentConfig.trustStore.isPresent()) {
            sslContextBuilder = sslContextBuilder
                    .loadTrustMaterial(readStore(agentConfig.trustStore.get(), agentConfig.trustStorePassword), null);
        } else if (agentConfig.trustCerts) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(TrustAllStrategy.INSTANCE);
        }
        if (agentConfig.keyStore.isPresent()) {
            String keyPassword = agentConfig.keyPassword.orElse(agentConfig.keyStorePassword.orElse(""));
            sslContextBuilder = sslContextBuilder.loadKeyMaterial(
                    readStore(agentConfig.keyStore.get(), agentConfig.keyStorePassword), keyPassword.toCharArray());
        }
        return new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | IOException | CertificateException
            | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: TruststoreSSLContextUtils.java    From knox with Apache License 2.0 6 votes vote down vote up
public static SSLContext getTruststoreSSLContext(KeystoreService keystoreService) {
  SSLContext sslContext = null;
  try {
    if(keystoreService != null) {
      KeyStore truststore = keystoreService.getTruststoreForHttpClient();
      if (truststore != null) {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        sslContextBuilder.loadTrustMaterial(truststore, null);
        sslContext = sslContextBuilder.build();
      }
    }
  } catch (KeystoreServiceException | NoSuchAlgorithmException | KeyStoreException
               | KeyManagementException e) {
    LOGGER.failedToLoadTruststore(e.getMessage(), e);
  }
  return sslContext;
}
 
Example 6
Source File: JsonBimServerSSLClientFactory.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
private SSLContext sslContext(URL trustedCertificate) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, KeyManagementException {
  SSLContextBuilder sslContextBuilder = SSLContexts.custom();
  if(trustedCertificate != null) {
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null);  // initializes keystore
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = null;
    try (InputStream trustedCertStream = trustedCertificate.openStream()) {
      cert = cf.generateCertificate(trustedCertStream);
    }
    if (cert!=null) keystore.setCertificateEntry("onlyentry", cert);
    sslContextBuilder.loadTrustMaterial(keystore, null);
  }
  return sslContextBuilder.build();
}
 
Example 7
Source File: PostHTTP.java    From nifi with Apache License 2.0 5 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
    SSLContextBuilder builder = SSLContexts.custom();
    final String trustFilename = service.getTrustStoreFile();
    if (trustFilename != null) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
        final String alias = keystore.aliases().nextElement();
        final Certificate cert = keystore.getCertificate(alias);
        if (cert instanceof X509Certificate) {
            principal = ((X509Certificate) cert).getSubjectDN();
        }
    }

    builder = builder.setProtocol(service.getSslAlgorithm());

    final SSLContext sslContext = builder.build();
    return sslContext;
}
 
Example 8
Source File: SslTrusted.java    From verano-http with MIT License 5 votes vote down vote up
@Override
public final HttpClientBuilder apply(final HttpClientBuilder builder) {
    final SSLContext context;
    try {
        final SSLContextBuilder ssl = SSLContexts.custom();
        ssl.loadTrustMaterial((chain, type) -> true);
        context = ssl.build();
        //@checkstyle IllegalCatchCheck (1 lines)
    } catch (final Exception exp) {
        throw new IllegalStateException(exp);
    }
    return builder.setSSLSocketFactory(
        new SSLConnectionSocketFactory(context, (ctx, session) -> true)
    );
}
 
Example 9
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
private SSLContext getSSLContext() throws Exception {
  SSLContextBuilder sslContextBuilder = SSLContexts.custom();
  if (null != truststore && null != truststorePassword) {
    loadTrustStore(sslContextBuilder);
  }
  if (null != keystore && null != keystorePassword && null != keyPassword) {
    loadKeyStore(sslContextBuilder);
  }
  return sslContextBuilder.build();
}
 
Example 10
Source File: YouTrackClient.java    From vk-java-sdk with MIT License 5 votes vote down vote up
private SSLConnectionSocketFactory initSslContext(String keyStoreType, String keyStorePath, String keyStorePassword, String keyPassword,
                                                  String trustStoreType, String trustStorePath, String trustStorePassword)
        throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException, KeyManagementException {

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();

    if (StringUtils.isNoneBlank(keyStorePath)) {
        KeyStore keyStore = SslUtils.getStore(keyStoreType, keyStorePath, keyStorePassword);
        if (keyStore.size() == 0) {
            throw new IllegalStateException("Key store has no keys");
        }

        sslContextBuilder.loadKeyMaterial(keyStore, keyPassword.toCharArray());
    }

    if (StringUtils.isNoneBlank(trustStorePath)) {
        KeyStore trustStore = SslUtils.getStore(trustStoreType, trustStorePath, trustStorePassword);
        if (trustStore.size() == 0) {
            throw new IllegalStateException("Trust store has no keys");
        }

        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
    }

    return new SSLConnectionSocketFactory(
            sslContextBuilder.build(),
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
}
 
Example 11
Source File: SSLTestConfig.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a new SSLContext for jetty servers which have been configured based on the settings of 
 * this object.
 *
 * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking 
 * due to lack of entropy, also explicitly allows the use of self-signed 
 * certificates (since that's what is almost always used during testing).
 * almost always used during testing). 
 */
public SSLConfig buildServerSSLConfig() {
  if (!isSSLMode()) {
    return null;
  }

  return new SSLConfig(isSSLMode(), isClientAuthMode(), null, null, null, null) {
    @Override
    public SslContextFactory.Server createContextFactory() {
      SslContextFactory.Server factory = new SslContextFactory.Server();
      try {
        SSLContextBuilder builder = SSLContexts.custom();
        builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE);

        builder.loadKeyMaterial(buildKeyStore(keyStore, TEST_PASSWORD), TEST_PASSWORD.toCharArray());

        if (isClientAuthMode()) {
          builder.loadTrustMaterial(buildKeyStore(trustStore, TEST_PASSWORD), new TrustSelfSignedStrategy()).build();

        }
        factory.setSslContext(builder.build());
      } catch (Exception e) {
        throw new RuntimeException("ssl context init failure: " + e.getMessage(), e);
      }
      factory.setNeedClientAuth(isClientAuthMode());
      return factory;
    }
  };
}
 
Example 12
Source File: HttpClientHelper.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new HTTP client.
 *
 * @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate
 * @param disableHostnameVerification specifies whether to turn off hostname verification
 *
 * @return the HTTP client
 * @throws KeyStoreException if a key store exception occurs
 * @throws NoSuchAlgorithmException if a no such algorithm exception occurs
 * @throws KeyManagementException if key management exception
 */
public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate, Boolean disableHostnameVerification)
    throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException
{
    // Create an HTTP client builder.
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    // Create an SSL context builder.
    SSLContextBuilder sslContextBuilder = SSLContexts.custom();

    // If specified, setup a trust strategy that allows all certificates.
    if (BooleanUtils.isTrue(trustSelfSignedCertificate))
    {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    }

    // If specified, turn hostname verification off.
    HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification) ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER :
        SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;

    // Create and assign an SSL connection socket factory.
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);

    // Build and return an HTTP client.
    return httpClientBuilder.build();
}
 
Example 13
Source File: SSLSessionStrategyFactory.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * Build an {@link SSLSessionStrategy}.
 *
 * @param trustStore the trust store
 * @param trustStorePassword the truststore password (if any)
 * @param keyStore the keystore
 * @param keyStorePassword the keystore password (if any)
 * @param keyAliases the key aliases that are candidates for use (if any)
 * @param keyPassword the key password (if any)
 * @param allowedProtocols the allowed transport protocols.
 *            <strong><em>Avoid specifying insecure protocols</em></strong>
 * @param allowedCiphers allowed crypto ciphersuites, <tt>null</tt> to use system defaults
 * @param trustSelfSigned true if self signed certificates can be trusted.
 *             <strong><em>Use with caution</em></strong>
 * @param allowAnyHostname true if any hostname can be connected to (i.e. does not need to match
 *            certificate hostname). <strong><em>Do not use in production</em></strong>
 * @return the connection socket factory
 * @throws NoSuchAlgorithmException if the selected algorithm is not available on the system
 * @throws KeyStoreException if there was a problem with the keystore
 * @throws CertificateException if there was a problem with the certificate
 * @throws IOException if the truststore could not be found or was invalid
 * @throws KeyManagementException if there is a problem with keys
 * @throws UnrecoverableKeyException if the key cannot be recovered
 */
public static SSLSessionStrategy build(String trustStore,
        String trustStorePassword,
        String keyStore,
        String keyStorePassword,
        String[] keyAliases,
        String keyPassword,
        String[] allowedProtocols,
        String[] allowedCiphers,
        boolean allowAnyHostname,
        boolean trustSelfSigned)

throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {

    Args.notNull(allowedProtocols, "Allowed protocols"); //$NON-NLS-1$
    Args.notNull(allowedCiphers, "Allowed ciphers"); //$NON-NLS-1$

    TrustStrategy trustStrategy = trustSelfSigned ?  SELF_SIGNED : null;
    HostnameVerifier hostnameVerifier = allowAnyHostname ? ALLOW_ANY :
        SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    PrivateKeyStrategy privateKeyStrategy = keyAliases == null ? null : new SelectByAlias(keyAliases);
    boolean clientAuth = keyStore == null ? false : true;

    SSLContextBuilder builder = SSLContexts.custom();

    if (trustStore != null) {
        loadTrustMaterial(builder,
                new File(trustStore),
                trustStorePassword.toCharArray(),
                trustStrategy);
    }

    if (keyStore != null) {
        char[] ksp = keyStorePassword == null ? null : keyStorePassword.toCharArray();
        char[] kp = keyPassword == null ? null : keyPassword.toCharArray();
        loadKeyMaterial(builder, new File(keyStore), ksp, kp, privateKeyStrategy);
    }

    SSLContext sslContext = builder.build();
    return new SSLSessionStrategy(hostnameVerifier, new CipherSelectingSSLSocketFactory(
            sslContext.getSocketFactory(), allowedCiphers, allowedProtocols, clientAuth));
}
 
Example 14
Source File: DefaultHttpClientFactory.java    From knox with Apache License 2.0 4 votes vote down vote up
/**
 * Conditionally creates a custom {@link SSLContext} based on the Gateway's configuration and whether
 * two-way SSL is enabled or not.
 * <p>
 * If two-way SSL is enabled, then a context with the Gateway's identity and a configured trust store
 * is created.  The trust store is forced to be the same as the identity's keystore if an explicit
 * trust store is not configured.
 * <p>
 * If two-way SSL is not enabled and an explict trust store is configured, then a context with the
 * configured trust store is created.
 * <p>
 * Else, a custom context is not crated and <code>null</code> is returned.
 * <p>
 * This method is package private to allow access to unit tests
 *
 * @param services     the {@link GatewayServices}
 * @param filterConfig a {@link FilterConfig} used to query for parameters for this operation
 * @param serviceRole the name of the service role to whom this HTTP client is being created for
 * @return a {@link SSLContext} or <code>null</code> if a custom {@link SSLContext} is not needed.
 */
SSLContext createSSLContext(GatewayServices services, FilterConfig filterConfig, String serviceRole) {
  KeyStore identityKeystore;
  char[] identityKeyPassphrase;
  KeyStore trustKeystore;

  KeystoreService ks = services.getService(ServiceType.KEYSTORE_SERVICE);
  try {
    if (Boolean.parseBoolean(filterConfig.getInitParameter(PARAMETER_USE_TWO_WAY_SSL))) {
      LOG.usingTwoWaySsl(serviceRole);
      AliasService as = services.getService(ServiceType.ALIAS_SERVICE);

      // Get the Gateway's configured identity keystore and key passphrase
      identityKeystore = ks.getKeystoreForGateway();
      identityKeyPassphrase = as.getGatewayIdentityPassphrase();

      // The trustKeystore will be the same as the identityKeystore if a truststore was not explicitly
      // configured in gateway-site (gateway.truststore.password.alias, gateway.truststore.path, gateway.truststore.type)
      // This was the behavior before KNOX-1812
      trustKeystore = ks.getTruststoreForHttpClient();
      if (trustKeystore == null) {
        trustKeystore = identityKeystore;
      }
    } else {
      // If not using twoWaySsl, there is no need to calculate the Gateway's identity keystore or
      // identity key.
      identityKeystore = null;
      identityKeyPassphrase = null;

      // The behavior before KNOX-1812 was to use the HttpClients default SslContext. However,
      // if a truststore was explicitly configured in gateway-site (gateway.truststore.password.alias,
      // gateway.truststore.path, gateway.truststore.type) create a custom SslContext and use it.
      trustKeystore = ks.getTruststoreForHttpClient();
    }

    // If an identity keystore or a trust store needs to be set, create and return a custom
    // SSLContext; else return null.
    if ((identityKeystore != null) || (trustKeystore != null)) {
      SSLContextBuilder sslContextBuilder = SSLContexts.custom();

      if (identityKeystore != null) {
        sslContextBuilder.loadKeyMaterial(identityKeystore, identityKeyPassphrase);
      }

      if (trustKeystore != null) {
        sslContextBuilder.loadTrustMaterial(trustKeystore, null);
      }

      return sslContextBuilder.build();
    } else {
      return null;
    }
  } catch (Exception e) {
    throw new IllegalArgumentException("Unable to create SSLContext", e);
  }
}
 
Example 15
Source File: SettingsBasedSSLConfiguratorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private SSLContext createSSLContext(String trustStorePath, String keyStorePath, String password) {

            try {
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore trustStore = KeyStore.getInstance("JKS");
                InputStream trustStream = new FileInputStream(
                        FileHelper.getAbsoluteFilePathFromClassPath(trustStorePath).toFile());
                trustStore.load(trustStream, password.toCharArray());
                tmf.init(trustStore);

                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                KeyStore keyStore = KeyStore.getInstance("JKS");

                Path path = FileHelper.getAbsoluteFilePathFromClassPath(keyStorePath);

                if (path == null) {
                    throw new RuntimeException("Could not find " + keyStorePath);
                }

                InputStream keyStream = new FileInputStream(path.toFile());

                keyStore.load(keyStream, password.toCharArray());
                kmf.init(keyStore, password.toCharArray());

                SSLContextBuilder sslContextBuilder = SSLContexts.custom();

                sslContextBuilder.loadTrustMaterial(trustStore, null);

                sslContextBuilder.loadKeyMaterial(keyStore, password.toCharArray(), new PrivateKeyStrategy() {

                    @Override
                    public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                        return "node1";
                    }
                });

                return sslContextBuilder.build();
            } catch (GeneralSecurityException | IOException e) {
                throw new RuntimeException(e);
            }
        }
 
Example 16
Source File: KeySetRetrieverTest.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@Test
public void clientCertTest() throws Exception {

    try (MockIpdServer sslMockIdpServer = new MockIpdServer(TestJwk.Jwks.ALL, SocketUtils.findAvailableTcpPort(),
            true) {
        @Override
        protected void handleDiscoverRequest(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {

            MockIpdServer.SSLTestHttpServerConnection connection = (MockIpdServer.SSLTestHttpServerConnection) ((HttpCoreContext) context)
                    .getConnection();

            X509Certificate peerCert = (X509Certificate) connection.getPeerCertificates()[0];

            try {
                String sha256Fingerprint = Hashing.sha256().hashBytes(peerCert.getEncoded()).toString();

                Assert.assertEquals("04b2b8baea7a0a893f0223d95b72081e9a1e154a0f9b1b4e75998085972b1b68",
                        sha256Fingerprint);

            } catch (CertificateEncodingException e) {
                throw new RuntimeException(e);
            }

            super.handleDiscoverRequest(request, response, context);
        }
    }) {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        KeyStore trustStore = KeyStore.getInstance("JKS");
        InputStream trustStream = new FileInputStream(
                FileHelper.getAbsoluteFilePathFromClassPath("jwt/truststore.jks").toFile());
        trustStore.load(trustStream, "changeit".toCharArray());

        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream keyStream = new FileInputStream(
                FileHelper.getAbsoluteFilePathFromClassPath("jwt/spock-keystore.jks").toFile());

        keyStore.load(keyStream, "changeit".toCharArray());

        sslContextBuilder.loadTrustMaterial(trustStore, null);

        sslContextBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray(), new PrivateKeyStrategy() {

            @Override
            public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                return "spock";
            }
        });

        SettingsBasedSSLConfigurator.SSLConfig sslConfig = new SettingsBasedSSLConfigurator.SSLConfig(
                sslContextBuilder.build(), new String[] { "TLSv1.2", "TLSv1.1" }, null, null, false, false, false,
                trustStore, null, keyStore, null, null);

        KeySetRetriever keySetRetriever = new KeySetRetriever(sslMockIdpServer.getDiscoverUri(), sslConfig, false);

        keySetRetriever.get();

    }
}
 
Example 17
Source File: HttpClient.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private final HttpAsyncClientBuilder asyncClientBuilder(HttpAsyncClientBuilder httpClientBuilder)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {

    // basic auth
    // pki auth

    if (ssl) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        if (log.isTraceEnabled()) {
            log.trace("Configure HTTP client with SSL");
        }

        if (trustStore != null) {
            sslContextBuilder.loadTrustMaterial(trustStore, null);
        }

        if (keystore != null) {
            sslContextBuilder.loadKeyMaterial(keystore, keyPassword, new PrivateKeyStrategy() {

                @Override
                public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                    if(aliases == null || aliases.isEmpty()) {
                        return keystoreAlias;
                    }

                    if(keystoreAlias == null || keystoreAlias.isEmpty()) {
                        return aliases.keySet().iterator().next();
                    }

                    return keystoreAlias;                    }
            });
        }

        final HostnameVerifier hnv = verifyHostnames?new DefaultHostnameVerifier():NoopHostnameVerifier.INSTANCE;

        final SSLContext sslContext = sslContextBuilder.build();
        httpClientBuilder.setSSLStrategy(new SSLIOSessionStrategy(
                sslContext,
                supportedProtocols,
                supportedCipherSuites,
                hnv
                ));
    }

    if (basicCredentials != null) {
        httpClientBuilder.setDefaultHeaders(Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials)));
    }

    // TODO: set a timeout until we have a proper way to deal with back pressure
    int timeout = 5;

    RequestConfig config = RequestConfig.custom()
      .setConnectTimeout(timeout * 1000)
      .setConnectionRequestTimeout(timeout * 1000)
      .setSocketTimeout(timeout * 1000).build();

    httpClientBuilder.setDefaultRequestConfig(config);

    return httpClientBuilder;

}