Java Code Examples for org.apache.http.ssl.SSLContextBuilder#loadTrustMaterial()

The following examples show how to use org.apache.http.ssl.SSLContextBuilder#loadTrustMaterial() . 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: GetHTTP.java    From nifi with Apache License 2.0 8 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 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: 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 4
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 5
Source File: ServerHttpsRequestIntegrationTests.java    From java-technology-stack 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 6
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 7
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 8
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 9
Source File: ClientProvider.java    From james-project with Apache License 2.0 5 votes vote down vote up
private SSLContextBuilder applyTrustStore(SSLContextBuilder sslContextBuilder) throws CertificateException, NoSuchAlgorithmException,
    KeyStoreException, IOException {

    SSLTrustStore trustStore = configuration.getSslConfiguration()
        .getTrustStore()
        .orElseThrow(() -> new IllegalStateException("SSLTrustStore cannot to be empty"));

    return sslContextBuilder
        .loadTrustMaterial(trustStore.getFile(), trustStore.getPassword());
}
 
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: RestClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private Registry constructRegistry() {

        try {
            SSLContextBuilder builder = SSLContextBuilder.create();

            builder.useProtocol(this.supportedProtocols[0]);

            if (!StringUtils.isNullOrEmpty(clientConfigurator.getCertificateFileName())) {
                builder.loadKeyMaterial(SslUtils.loadKeystore(clientConfigurator.getCertificateFileName(),
                                                              clientConfigurator.getCertificateFilePassword()),
                                        clientConfigurator.getCertificateFilePassword().toCharArray());
            }

            // Trust all certificates
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {

                    return true;
                }
            });
            SSLContext sslContext = builder.build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                                                                              new NoopHostnameVerifier());

            Registry registry = RegistryBuilder.create().register("https", sslsf).build();

            return registry;
        } catch (Exception e) {
            throw new RuntimeException("Unable to setup SSL context for REST client with Apache connector provider", e);
        }
    }
 
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: AzkabanAjaxAPIClient.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private static CloseableHttpClient getHttpClient()
    throws IOException {
  try {
    // Self sign SSL
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, (TrustStrategy) new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

    // Create client
    return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(new BasicCookieStore()).build();
  } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
    throw new IOException("Issue with creating http client", e);
  }
}
 
Example 14
Source File: DeviceSimulatorUpdater.java    From hawkbit-examples with Eclipse Public License 1.0 5 votes vote down vote up
private static CloseableHttpClient createHttpClientThatAcceptsAllServerCerts()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final SSLContextBuilder builder = SSLContextBuilder.create();
    builder.loadTrustMaterial(null, (chain, authType) -> true);
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
 
Example 15
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 16
Source File: CmmnHttpActivityBehaviorImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected HttpActivityExecutor createHttpActivityExecutor() {
    HttpClientConfig config = CommandContextUtil.getCmmnEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    // client builder settings
    if (config.isUseSystemProperties()) {
        httpClientBuilder.useSystemProperties();
    }

    return new HttpActivityExecutor(httpClientBuilder, new NopErrorPropagator(),
            CommandContextUtil.getCmmnEngineConfiguration().getObjectMapper());
}
 
Example 17
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
protected void loadTrustStore(SSLContextBuilder sslContextBuilder) throws Exception {
  sslContextBuilder.loadTrustMaterial(truststore, truststorePassword.toCharArray());
}
 
Example 18
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 19
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 20
Source File: AbstractUnitTest.java    From deprecated-security-ssl with Apache License 2.0 2 votes vote down vote up
protected final CloseableHttpClient getHTTPClient() throws Exception {

        final HttpClientBuilder hcb = HttpClients.custom();

        if (enableHTTPClientSSL) {

            log.debug("Configure HTTP client with SSL");

            final KeyStore myTrustStore = KeyStore.getInstance("JKS");
            myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks").toFile()), "changeit".toCharArray());

            final KeyStore keyStore = KeyStore.getInstance(keystore.toLowerCase().endsWith("p12")?"PKCS12":"JKS");
            keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath(keystore).toFile()), "changeit".toCharArray());

            final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useProtocol("TLS");

            if (trustHTTPServerCertificate) {
                sslContextbBuilder.loadTrustMaterial(myTrustStore, null);
            }

            if (sendHTTPClientCertificate) {
                sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
            }
            
            final SSLContext sslContext = sslContextbBuilder.build();

            String[] protocols = null;

            if (enableHTTPClientSSLv3Only) {
                protocols = new String[] { "SSLv3" };
            } else {
                protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
            }
            
            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null, NoopHostnameVerifier.INSTANCE);

            hcb.setSSLSocketFactory(sslsf);
        }

        hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

        return hcb.build();
    }