org.apache.http.ssl.SSLContextBuilder Java Examples

The following examples show how to use org.apache.http.ssl.SSLContextBuilder. 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: RestClientCertTestConfiguration.java    From spring-boot-rest-clientcertificate with MIT License 8 votes vote down vote up
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception {

    SSLContext sslContext = SSLContextBuilder
            .create()
            .loadKeyMaterial(ResourceUtils.getFile("classpath:keystore.jks"), allPassword, allPassword)
            .loadTrustMaterial(ResourceUtils.getFile("classpath:truststore.jks"), allPassword)
            .build();

    HttpClient client = HttpClients.custom()
            .setSSLContext(sslContext)
            .build();

    return builder
            .requestFactory(new HttpComponentsClientHttpRequestFactory(client))
            .build();
}
 
Example #2
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 #3
Source File: ThriftOverHttp1Test.java    From armeria with Apache License 2.0 7 votes vote down vote up
@Override
protected TTransport newTransport(String uri, HttpHeaders headers) throws TTransportException {
    final SSLContext sslContext;
    try {
        sslContext = SSLContextBuilder.create()
                                      .loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
                                      .build();
    } catch (GeneralSecurityException e) {
        throw new TTransportException("failed to initialize an SSL context", e);
    }

    final THttpClient client = new THttpClient(
            uri, HttpClientBuilder.create()
                                  .setSSLHostnameVerifier((hostname, session) -> true)
                                  .setSSLContext(sslContext)
                                  .build());
    client.setCustomHeaders(
            headers.names().stream()
                   .collect(toImmutableMap(AsciiString::toString,
                                           name -> String.join(", ", headers.getAll(name)))));
    return client;
}
 
Example #4
Source File: ServerHttpsRequestIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	this.server.setHandler(new CheckRequestHandler());
	this.server.afterPropertiesSet();
	this.server.start();

	// Set dynamically chosen port
	this.port = this.server.getPort();

	SSLContextBuilder builder = new SSLContextBuilder();
	builder.loadTrustMaterial(new TrustSelfSignedStrategy());
	SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
			builder.build(), NoopHostnameVerifier.INSTANCE);
	CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
			socketFactory).build();
	HttpComponentsClientHttpRequestFactory requestFactory =
			new HttpComponentsClientHttpRequestFactory(httpclient);
	this.restTemplate = new RestTemplate(requestFactory);
}
 
Example #5
Source File: SecurityUtils.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    sslcontextBuilder.setProtocol("TLSv1.2");

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
Example #6
Source File: SSLSessionStrategyFactory.java    From apiman with Apache License 2.0 6 votes vote down vote up
private static SSLContextBuilder loadKeyMaterial(SSLContextBuilder builder, File file, char[] ksp,
        char[] kp, PrivateKeyStrategy privateKeyStrategy) throws NoSuchAlgorithmException,
                KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
    Args.notNull(file, "Keystore file"); //$NON-NLS-1$
    final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {
        identityStore.load(instream, ksp);
    } finally {
        instream.close();
    }
    return builder.loadKeyMaterial(identityStore, kp, privateKeyStrategy);
}
 
Example #7
Source File: IftttIndegoAdapter.java    From iot-device-bosch-indego-controller with Apache License 2.0 6 votes vote down vote up
/**
 * This creates a HTTP client instance for connecting the IFTTT server.
 * 
 * @return the HTTP client instance
 */
private CloseableHttpClient buildHttpClient ()
{
    if ( configuration.isIftttIgnoreServerCertificate() ) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted (X509Certificate[] chain_, String authType_) throws CertificateException
                {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        }
        catch (Exception ex) {
            LOG.error(ex);
            // This should never happen, but we have to handle it
            throw new RuntimeException(ex);
        }
    }
    else {
        return HttpClients.createDefault();
    }
}
 
Example #8
Source File: CustomHttpClient.java    From zerocode with Apache License 2.0 6 votes vote down vote up
/**
 * This method has been overridden here simply to show how a custom/project-specific http client
 * can be plugged into the framework.
 *
 * e.g. You can create your own project specific http client needed for http/https/tls connections or
 * a Corporate proxy based Http client here.
 * Sometimes you may need a simple default http client
 * e.g. HttpClients.createDefault() provided by Apache lib.
 *
 * Note:
 * If you do not override this method, the framework anyways creates a http client suitable for both http/https.
 */
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .build();
}
 
Example #9
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 6 votes vote down vote up
public CustomHttpClient(String url, String user, String pass) throws Exception {
	this.openviduUrl = url.replaceFirst("/*$", "");
	this.headerAuth = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes());

	SSLContext sslContext = null;
	try {
		sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy() {
			public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				return true;
			}
		}).build();
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		throw new Exception("Error building custom HttpClient: " + e.getMessage());
	}
	HttpClient unsafeHttpClient = HttpClients.custom().setSSLContext(sslContext)
			.setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
	Unirest.setHttpClient(unsafeHttpClient);
}
 
Example #10
Source File: ClientConnection.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static PoolingHttpClientConnectionManager getConnctionManager(){

        Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
        try {
            SSLConnectionSocketFactory trustSelfSignedSocketFactory = new SSLConnectionSocketFactory(
                        new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                        new TrustAllHostNameVerifier());
            socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory> create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", trustSelfSignedSocketFactory)
                    .build();
        } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
            Data.logger.warn("", e);
        }
        
        PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? 
                new PoolingHttpClientConnectionManager(socketFactoryRegistry):
                new PoolingHttpClientConnectionManager();
        
        // twitter specific options
        cm.setMaxTotal(2000);
        cm.setDefaultMaxPerRoute(200);
        
        return cm;
    }
 
Example #11
Source File: HttpClientServiceImpl.java    From smockin with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient noSslHttpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {

        final SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(null, (x509CertChain, authType) -> true)
                .build();

        return HttpClientBuilder.create()
                .setSSLContext(sslContext)
                .setConnectionManager(
                        new PoolingHttpClientConnectionManager(
                                RegistryBuilder.<ConnectionSocketFactory>create()
                                        .register("http", PlainConnectionSocketFactory.INSTANCE)
                                        .register("https", new SSLConnectionSocketFactory(sslContext,
                                                NoopHostnameVerifier.INSTANCE))
                                        .build()
                        ))
                .build();
    }
 
Example #12
Source File: HttpClientWrapper.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
public static void enabledSSL() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(100);
    client = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .setConnectionManager(cm)
            .build();
}
 
Example #13
Source File: CrossOriginResourceSharingResponseTest.java    From s3proxy with Apache License 2.0 6 votes vote down vote up
private static CloseableHttpClient getHttpClient() throws
        KeyManagementException, NoSuchAlgorithmException,
        KeyStoreException {
    // Relax SSL Certificate check
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
            null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] arg0,
                        String arg1) throws CertificateException {
                    return true;
                }
            }).build();

    Registry<ConnectionSocketFactory> registry = RegistryBuilder
            .<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE)).build();

    PoolingHttpClientConnectionManager connectionManager = new
            PoolingHttpClientConnectionManager(registry);

    return HttpClients.custom().setConnectionManager(connectionManager)
            .build();
}
 
Example #14
Source File: HttpClientPool.java    From FATE-Serving with Apache License 2.0 6 votes vote down vote up
public static void initPool() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
                Dict.HTTPS, sslsf).build();
        poolConnManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        poolConnManager.setMaxTotal(500);
        poolConnManager.setDefaultMaxPerRoute(200);
        int socketTimeout = 10000;
        int connectTimeout = 10000;
        int connectionRequestTimeout = 10000;
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                connectTimeout).build();
        httpClient = getConnection();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        logger.error("init http client pool failed:", ex);
    }
}
 
Example #15
Source File: HttpsClientSslLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
    final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
        .build();
    final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();

    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    final CloseableHttpClient httpClient = HttpClients.custom()
        .setSSLHostnameVerifier(hostnameVerifier)
        .setSSLSocketFactory(sslsf)
        .build();

    // new

    final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
    final HttpResponse response = httpClient.execute(getMethod);
    assertThat(response.getStatusLine()
        .getStatusCode(), equalTo(200));
    httpClient.close();

}
 
Example #16
Source File: HttpsClientSslLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
    final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
        .build();

    final CloseableHttpClient client = HttpClients.custom()
        .setSSLContext(sslContext)
        .setSSLHostnameVerifier(new NoopHostnameVerifier())
        .build();
    final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
    httpGet.setHeader("Accept", "application/xml");

    final HttpResponse response = client.execute(httpGet);
    assertThat(response.getStatusLine()
        .getStatusCode(), equalTo(200));
}
 
Example #17
Source File: ClientOptionsTest.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testCreate() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslContext = new SSLContextBuilder().build();
    ClientOptions options = ClientOptions.builder()
            .setConnectionPoolSizePerRoute(2)
            .setConnectionPoolTotalSize(50)
            .setConnectTimeout(100)
            .setSocketTimeout(1000)
            .setRetryCount(5)
            .setSslContext(sslContext)
            .setShardWidth(1024)
            .build();
    assertEquals(2, options.getConnectionPoolSizePerRoute());
    assertEquals(50, options.getConnectionPoolTotalSize());
    assertEquals(100, options.getConnectTimeout());
    assertEquals(1000, options.getSocketTimeout());
    assertEquals(5, options.getRetryCount());
    assertEquals(sslContext, options.getSslContext());
    assertEquals(1024, options.getShardWidth());
}
 
Example #18
Source File: HunterRequest.java    From Burp-Hunter with GNU General Public License v3.0 6 votes vote down vote up
public String notifyHunter(byte[] content) throws IOException {
    try {
        String request = new String(content);
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
        HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
        String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
        StringEntity entity = new StringEntity(json);
        entity.setContentType("applicaiton/json");
        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);
        String responseString = new BasicResponseHandler().handleResponse(response);
        return responseString;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        
        Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "Error Notifying Probe Server!";
}
 
Example #19
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #20
Source File: APIImportConfigAdapter.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory createSSLContext() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
	SSLContextBuilder builder = new SSLContextBuilder();
	builder.loadTrustMaterial(null, new TrustAllStrategy());
	
	String keyStorePath=System.getProperty("javax.net.ssl.keyStore","");
	if (StringUtils.isNotEmpty(keyStorePath)) {
		String keyStorePassword=System.getProperty("javax.net.ssl.keyStorePassword","");
		if (StringUtils.isNotEmpty(keyStorePassword)) {
			String keystoreType=System.getProperty("javax.net.ssl.keyStoreType",KeyStore.getDefaultType());
			LOG.debug("Reading keystore from {}",keyStorePath);
			KeyStore ks = KeyStore.getInstance(keystoreType);
			ks.load(new FileInputStream(new File(keyStorePath)), keyStorePassword.toCharArray());				
			builder.loadKeyMaterial(ks,keyStorePassword.toCharArray());
		}
	} else {
		LOG.debug("NO javax.net.ssl.keyStore property.");
	}
	String [] tlsProts = getAcceptedTLSProtocols();
	SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
			builder.build(),
               tlsProts,
               null,
               new NoopHostnameVerifier());
	return sslsf;
}
 
Example #21
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 #22
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #23
Source File: GetHTTP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())){
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example #24
Source File: GerritChecksApiBuilder.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
public GerritChecksApiBuilder allowInsecureHttps() {
  try {
    SSLContext sslContext =
        new SSLContextBuilder()
            .loadTrustMaterial(
                null,
                new TrustStrategy() {
                  public boolean isTrusted(final X509Certificate[] chain, String authType)
                      throws CertificateException {
                    return true;
                  }
                })
            .build();
    SSLConnectionSocketFactory sslsf =
        new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    clientBuilder.setSSLSocketFactory(sslsf);
  } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
    LOGGER.log(Level.WARNING, "Could not disable SSL verification.", e);
  }
  return this;
}
 
Example #25
Source File: AbstractGremlinServerChannelizerIntegrateTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createSslHttpClient() throws Exception {
    final SSLContextBuilder wsBuilder = new SSLContextBuilder();
    wsBuilder.loadTrustMaterial(null, (chain, authType) -> true);
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wsBuilder.build(),
        new NoopHostnameVerifier());
    //This winds up using a PoolingHttpClientConnectionManager so need to pass the
    //RegistryBuilder
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder
        .<ConnectionSocketFactory> create().register("https", sslsf)
        .build();
    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    return HttpClients
        .custom()
        .setConnectionManager(cm)
        .build();

}
 
Example #26
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 #27
Source File: SslTrustCorporateProxyHttpClient.java    From zerocode with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    LOGGER.info("###Used SSL Enabled Http Client with Corporate Proxy, for both Http and Https connections");

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();

    CookieStore cookieStore = new BasicCookieStore();

    CredentialsProvider credsProvider = createProxyCredentialsProvider(proxyHost, proxyPort, proxyUserName, proxyPassword);

    HttpHost proxy = new HttpHost(proxyHost, proxyPort);

    return HttpClients.custom()
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credsProvider)
            .setProxy(proxy)
            .build();
}
 
Example #28
Source File: AbstractHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
/**
 * custom http client for server with SSL errors
 *
 * @return
 */
public final CloseableHttpClient getCustomClient() {
    try {
        HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                (TrustStrategy) (X509Certificate[] arg0, String arg1) -> true).build();
        builder.setSSLContext(sslContext);
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        builder.setConnectionManager(connMgr);
        return builder.build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }
    return getSystemClient();
}
 
Example #29
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private void loadKeyMaterial(SSLContextBuilder sslContextBuilder) throws NoSuchAlgorithmException,
        KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
    if (config.getKeyStore() != null) {
        sslContextBuilder.setKeyStoreType(config.getKeyStoreType()).setProtocol(config.getProtocol());

        if (!config.getKeyStore().startsWith(SecurityUtils.SAFKEYRING)) {
            loadKeystoreMaterial(sslContextBuilder);
        } else {
            loadKeyringMaterial(sslContextBuilder);
        }
    } else {
        log.info("No key store is defined");
        KeyStore emptyKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
        emptyKeystore.load(null, null);
        usedKeyStore = emptyKeystore;
        sslContextBuilder.loadKeyMaterial(emptyKeystore, null);
    }
}
 
Example #30
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
private void loadKeystoreMaterial(SSLContextBuilder sslContextBuilder) throws UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    if (config.getKeyStore() == null) {
        apimlLog.log("org.zowe.apiml.common.keystoreNotDefined");
        throw new HttpsConfigError("server.ssl.keyStore configuration parameter is not defined",
                ErrorCode.KEYSTORE_NOT_DEFINED, config);
    }
    if (config.getKeyStorePassword() == null) {
        apimlLog.log("org.zowe.apiml.common.keystorePasswordNotDefined");
        throw new HttpsConfigError("server.ssl.keyStorePassword configuration parameter is not defined",
                ErrorCode.KEYSTORE_PASSWORD_NOT_DEFINED, config);
    }
    log.info("Loading key store file: " + config.getKeyStore());
    File keyStoreFile = new File(config.getKeyStore());
    sslContextBuilder.loadKeyMaterial(keyStoreFile,
            config.getKeyStorePassword() == null ? null : config.getKeyStorePassword().toCharArray(),
            config.getKeyPassword() == null ? null : config.getKeyPassword().toCharArray());
}