Java Code Examples for org.apache.http.conn.ssl.SSLConnectionSocketFactory#getDefaultHostnameVerifier()

The following examples show how to use org.apache.http.conn.ssl.SSLConnectionSocketFactory#getDefaultHostnameVerifier() . 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: MPRestClient.java    From dx-java with MIT License 10 votes vote down vote up
/**
 * Create a HttpClient
 * @return a HttpClient
 */
private HttpClient createHttpClient() {
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[]{"TLSv1.1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(MercadoPago.SDK.getMaxConnections());
    connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
    connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);

    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(), false);

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new KeepAliveStrategy())
            .setRetryHandler(retryHandler)
            .disableCookieManagement()
            .disableRedirectHandling();

    return httpClientBuilder.build();
}
 
Example 2
Source File: ApiHeadersTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpsDoesNotReturnJettyServerVersionHeader() throws Exception {

  final HttpGet httpget = new HttpGet(httpsUri +  "/test/endpoint");

  // trust all self-signed certs and add the client keystore if it's configured.
  final SSLContext sslContext = SSLContexts.custom()
      .loadTrustMaterial(new TrustSelfSignedStrategy())
      .loadKeyMaterial(new File(clientKeystoreLocation),SSL_PASSWORD.toCharArray(),
          SSL_PASSWORD.toCharArray())
      .build();

  final SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"},
      null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

  try ( CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslSf).build();
      CloseableHttpResponse response = httpclient.execute(httpget) ) {

    assertThat(response.getStatusLine().getStatusCode(), is(200));
    assertThat(response.getFirstHeader( "Server" ), is(nullValue()));
  }
}
 
Example 3
Source File: HttpUtils.java    From ScriptSpider with Apache License 2.0 6 votes vote down vote up
/**
 * 创建httpclient连接池,并初始化httpclient
 */
public void init() {
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslsf)
                .build();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // Increase max total connection to 200
        httpClientConnectionManager.setMaxTotal(maxTotalPool);
        // Increase default max connection per route to 20
        httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
        httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
    } catch (Exception e) {

    }
}
 
Example 4
Source File: TagMeAnnotator.java    From gerbil with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void init() throws GerbilException {
    HttpClientBuilder builder = HttpManagement.getInstance().generateHttpClientBuilder();
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream instream = this.getClass().getClassLoader().getResourceAsStream(KEY_STORE_RESOURCE_NAME);
        try {
            keyStore.load(instream, KEY_STORE_PASSWORD);
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
                .build();
        builder.setSSLContext(sslcontext);

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
        CloseableHttpClient localClient = builder.build();
        this.setClient(localClient);
    } catch (Exception e) {
        throw new GerbilException("Couldn't initialize SSL context.", e, ErrorTypes.ANNOTATOR_LOADING_ERROR);
    }
    this.setClient(builder.build());
}
 
Example 5
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the {@code HostnameVerifier} given the provided {@code verification}.
 *
 * @param verification The intended hostname verification action.
 * @return A verifier for the request verification.
 * @throws IllegalArgumentException if the provided verification cannot be handled.
 */
HostnameVerifier getHostnameVerifier(HostnameVerification verification) {
  // Normally, the configuration logic would give us a default of STRICT if it was not
  // provided by the user. It's easy for us to do a double-check.
  if (verification == null) {
    verification = HostnameVerification.STRICT;
  }
  switch (verification) {
  case STRICT:
    return SSLConnectionSocketFactory.getDefaultHostnameVerifier();
  case NONE:
    return NoopHostnameVerifier.INSTANCE;
  default:
    throw new IllegalArgumentException("Unhandled HostnameVerification: "
        + hostnameVerification);
  }
}
 
Example 6
Source File: WxSslClient.java    From weixin-sdk with Apache License 2.0 6 votes vote down vote up
public WxSslClient(String certPath, String certPassword) {
    KeyStore keyStore = null;
    SSLContext sslcontext = null;
    try {
        keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream inputStream = new FileInputStream(new File(certPath));
        keyStore.load(inputStream, certPassword.toCharArray());
        sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, certPassword.toCharArray()).build();
    } catch (Exception e) {
        logger.error("initializing WxHttpsClient failed.", e);
        throw new WxRuntimeException(999, e.getMessage());
    }

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();;

    requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(30000).setConnectionRequestTimeout(30000).build();

}
 
Example 7
Source File: ClickHouseHttpClientBuilder.java    From clickhouse-jdbc with Apache License 2.0 6 votes vote down vote up
private PoolingHttpClientConnectionManager getConnectionManager()
    throws CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {
    RegistryBuilder<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
      .register("http", PlainConnectionSocketFactory.getSocketFactory());

    if (properties.getSsl()) {
        HostnameVerifier verifier = "strict".equals(properties.getSslMode()) ? SSLConnectionSocketFactory.getDefaultHostnameVerifier() : NoopHostnameVerifier.INSTANCE;
        registry.register("https", new SSLConnectionSocketFactory(getSSLContext(), verifier));
    }

    //noinspection resource
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
        registry.build(),
        null,
        null,
        new IpVersionPriorityResolver(),
        properties.getTimeToLiveMillis(),
        TimeUnit.MILLISECONDS
    );

    connectionManager.setDefaultMaxPerRoute(properties.getDefaultMaxPerRoute());
    connectionManager.setMaxTotal(properties.getMaxTotal());
    connectionManager.setDefaultConnectionConfig(getConnectionConfig());
    return connectionManager;
}
 
Example 8
Source File: PGPKeysServerClientHttps.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected PGPKeysServerClientHttps(URI uri, int connectTimeout, int readTimeout, int maxAttempts, Proxy proxy)
        throws IOException {

    super(prepareKeyServerURI(uri), connectTimeout, readTimeout, maxAttempts, proxy);

    try {
        if (uri.getHost().toLowerCase(Locale.ROOT).endsWith("sks-keyservers.net")) {
            final CertificateFactory cf = CertificateFactory.getInstance("X.509");
            final Certificate ca = cf.generateCertificate(
                    getClass().getClassLoader().getResourceAsStream("sks-keyservers.netCA.pem"));

            final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            final TrustManagerFactory tmf
                    = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);

            final SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            this.sslSocketFactory
                    = new SSLConnectionSocketFactory(
                    context, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        } else {
            this.sslSocketFactory = SSLConnectionSocketFactory.getSystemSocketFactory();
        }
    } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
        throw new IOException(e);
    }
}
 
Example 9
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
public HostnameVerifier createHostnameVerifier() {
    if (config.isVerifySslCertificatesOfServices()) {
        return SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    } else {
        return new NoopHostnameVerifier();
    }
}
 
Example 10
Source File: HttpsClientProvider.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create Http Configuration with defaults for maximum of connections and maximum of connections per route.
 */
private HttpClientBuilder sharedHttpClientConfiguration(SSLContext sslContext) {
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
        SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    return HttpClients.custom()
        .setSSLSocketFactory(sslsf)
        .setDefaultRequestConfig(this.requestConfig)
        .setMaxConnTotal(3 * 3)
        .setMaxConnPerRoute(3);
}
 
Example 11
Source File: PilosaClient.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Registry<ConnectionSocketFactory> getRegistry() {
    HostnameVerifier verifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            this.options.getSslContext(),
            new String[]{"TLSv1.2"}, null, verifier);
    return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();
}
 
Example 12
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 13
Source File: SFSSLConnectionSocketFactory.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
public SFSSLConnectionSocketFactory(TrustManager[] trustManagers,
                                    boolean socksProxyDisabled)
throws NoSuchAlgorithmException, KeyManagementException
{
  super(
      initSSLContext(trustManagers),
      new String[]{SSL_VERSION},
      decideCipherSuites(),
      SSLConnectionSocketFactory.getDefaultHostnameVerifier()
  );
  this.socksProxyDisabled = socksProxyDisabled;
}
 
Example 14
Source File: WxBot.java    From WxBot with GNU General Public License v3.0 5 votes vote down vote up
public WxBot() {
	System.setProperty("jsse.enableSNIExtension", "false");
	System.setProperty("https.protocols", "TLSv1");

	try {
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
				new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
		httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
}
 
Example 15
Source File: HttpClientManagerImplIT.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void setSSL(HttpClientBuilder builder)
    throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException
{
  SSLContext sslContext = SSLContexts.custom()
      .loadTrustMaterial(this.getClass().getClassLoader().getResource("testkeystore"), "password".toCharArray(),
          new TrustSelfSignedStrategy())
      .build();
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null,
      SSLConnectionSocketFactory.getDefaultHostnameVerifier());
  builder.setSSLSocketFactory(sslsf);
}
 
Example 16
Source File: DatabricksRestClientImpl.java    From databricks-rest-client with Apache License 2.0 4 votes vote down vote up
protected void initClient(DatabricksServiceFactory.Builder builder) {

    HttpClientBuilder clientBuilder = HttpClients.custom().useSystemProperties()
        .setRetryHandler(retryHandler)
        .setServiceUnavailableRetryStrategy(retryStrategy)
        .setDefaultRequestConfig(createRequestConfig(builder));

    List<Header> headers = new ArrayList<>();
    if (isNotEmpty(builder.getToken())) {
      Header authHeader = new BasicHeader("Authorization", String.format("Bearer %s", builder.getToken()));
      headers.add(authHeader);
    } else { // password authorization
      CredentialsProvider credsProvider = new BasicCredentialsProvider();
      credsProvider.setCredentials(
          new AuthScope(host, HTTPS_PORT),
          new UsernamePasswordCredentials(builder.getUsername(), builder.getPassword()));

      clientBuilder.setDefaultCredentialsProvider(credsProvider);

    }

    String userAgent = builder.getUserAgent();
    if (userAgent != null && userAgent.length() > 0) {
      Header userAgentHeader = new BasicHeader("User-Agent", userAgent);
      headers.add(userAgentHeader);
    }

    if (!headers.isEmpty()) {
      clientBuilder.setDefaultHeaders(headers);
    }

    try {
      SSLContext ctx = SSLContext.getDefault();
      // Allow TLSv1.2 protocol only
      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
          ctx,
          new String[]{"TLSv1.2"},
          null,
          SSLConnectionSocketFactory.getDefaultHostnameVerifier());
      clientBuilder = clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
      logger.error("", e);
    }

    client = clientBuilder.build(); //CloseableHttpClient

    url = String.format("https://%s/api/%s", host, apiVersion);
    mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
  }
 
Example 17
Source File: HttpClientRestClient.java    From pardot-java-client with MIT License 4 votes vote down vote up
/**
 * Initialization method.  This takes in the configuration and sets up the underlying
 * http client appropriately.
 * @param configuration The user defined configuration.
 */
@Override
public void init(final Configuration configuration) {
    // Save reference to configuration
    this.configuration = configuration;

    // Load RequestMutator instance from configuration.
    requestInterceptor = configuration.getRequestInterceptor();

    // Create default SSLContext
    final SSLContext sslcontext = SSLContexts.createDefault();

    // Initialize ssl context with configured key and trust managers.
    try {
        sslcontext.init(new KeyManager[0], getTrustManagers(), new SecureRandom());
    } catch (final KeyManagementException exception) {
        throw new RuntimeException(exception.getMessage(), exception);
    }

    // Create hostname verifier instance.
    final HostnameVerifier hostnameVerifier;
    // Emit an warning letting everyone know we're using an insecure configuration.
    if (configuration.getIgnoreInvalidSslCertificates()) {
        logger.warn("Using insecure configuration, skipping server-side certificate validation checks.");

        // If we're configured to ignore invalid certificates, use the Noop verifier.
        hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    } else {
        // Use default implementation
        hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    }

    // Allow TLSv1_1 and TLSv1_2 protocols
    final LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1.1", "TLSv1.2" },
        null,
        hostnameVerifier
    );

    // Setup client builder
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder
        // Pardot disconnects requests after 120 seconds.
        .setConnectionTimeToLive(130, TimeUnit.SECONDS)
        .setSSLSocketFactory(sslsf);

    // Define our RequestConfigBuilder
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    // If we have a configured proxy host
    if (configuration.getProxyHost() != null) {
        // Define proxy host
        final HttpHost proxyHost = new HttpHost(
            configuration.getProxyHost(),
            configuration.getProxyPort(),
            configuration.getProxyScheme()
        );

        // If we have proxy auth enabled
        if (configuration.getProxyUsername() != null) {
            // Create credential provider
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(configuration.getProxyHost(), configuration.getProxyPort()),
                new UsernamePasswordCredentials(configuration.getProxyUsername(), configuration.getProxyPassword())
            );

            // Attach Credentials provider to client builder.
            clientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        // Attach Proxy to request config builder
        requestConfigBuilder.setProxy(proxyHost);
    }

    // Attach default request config
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    // build http client
    httpClient = clientBuilder.build();
}
 
Example 18
Source File: SslTest.java    From rest-utils with Apache License 2.0 4 votes vote down vote up
private int makeGetRequest(String url, String clientKeystoreLocation, String clientKeystorePassword,
                           String clientKeyPassword)
    throws Exception {
  log.debug("Making GET " + url);
  HttpGet httpget = new HttpGet(url);
  CloseableHttpClient httpclient;
  if (url.startsWith("http://")) {
    httpclient = HttpClients.createDefault();
  } else {
    // trust all self-signed certs.
    SSLContextBuilder sslContextBuilder = SSLContexts.custom()
            .loadTrustMaterial(new TrustSelfSignedStrategy());

    // add the client keystore if it's configured.
    if (clientKeystoreLocation != null) {
      sslContextBuilder.loadKeyMaterial(new File(clientKeystoreLocation),
              clientKeystorePassword.toCharArray(),
              clientKeyPassword.toCharArray());
    }
    SSLContext sslContext = sslContextBuilder.build();

    SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"},
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    httpclient = HttpClients.custom()
            .setSSLSocketFactory(sslSf)
            .build();
  }

  int statusCode = -1;
  CloseableHttpResponse response = null;
  try {
    response = httpclient.execute(httpget);
    statusCode = response.getStatusLine().getStatusCode();
  } finally {
    if (response != null) {
      response.close();
    }
    httpclient.close();
  }
  return statusCode;
}
 
Example 19
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 20
Source File: CoreUtils.java    From oxd with Apache License 2.0 3 votes vote down vote up
/**
 * @param pathToKeyStore path to key store, e.g. D:/Development/gluu_conf/etc/certs/DA855F9895A1CA3B9E7D4BF5-java.jks
 * @param password       key store password
 * @return http client
 * @throws Exception
 */


public static HttpClient createHttpClientWithKeyStore(File pathToKeyStore, String password, Optional<ProxyConfiguration> proxyConfiguration) throws Exception {

    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(pathToKeyStore, password.toCharArray())
            .build();

    SSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(
            sslcontext, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    return createClient(sslConSocFactory, proxyConfiguration);
}