Example usage for org.apache.http.conn.ssl SSLContextBuilder loadTrustMaterial

List of usage examples for org.apache.http.conn.ssl SSLContextBuilder loadTrustMaterial

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLContextBuilder loadTrustMaterial.

Prototype

public SSLContextBuilder loadTrustMaterial(final KeyStore truststore, final TrustStrategy trustStrategy)
            throws NoSuchAlgorithmException, KeyStoreException 

Source Link

Usage

From source file:com.kixeye.chassis.transport.HttpTransportTest.java

@Test
public void testHttpServiceWithJsonWithHTTPSAndHTTP() throws Exception {
    Map<String, Object> properties = new HashMap<String, Object>();

    properties.put("http.enabled", "true");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("https.enabled", "true");
    properties.put("https.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("https.hostname", "localhost");
    properties.put("https.selfSigned", "true");

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestRestService.class);

    try {//from   w  w w.j a  v a2s  . com
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        SSLContext sslContext = builder.build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new X509HostnameVerifier() {
                    @Override
                    public void verify(String host, SSLSocket ssl) throws IOException {
                    }

                    @Override
                    public void verify(String host, X509Certificate cert) throws SSLException {
                    }

                    @Override
                    public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
                    }

                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                });

        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory()).build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(HttpClients.custom().setConnectionManager(cm).build());

        RestTemplate httpClient = new RestTemplate(requestFactory);
        httpClient.setErrorHandler(new ResponseErrorHandler() {
            public boolean hasError(ClientHttpResponse response) throws IOException {
                return response.getRawStatusCode() == HttpStatus.OK.value();
            }

            public void handleError(ClientHttpResponse response) throws IOException {

            }
        });

        httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
        httpClient.setMessageConverters(new ArrayList<HttpMessageConverter<?>>(
                Lists.newArrayList(new SerDeHttpMessageConverter(serDe))));

        TestObject response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.postForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject("more stuff"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        ResponseEntity<ServiceError> error = httpClient.postForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("https://localhost:" + properties.get("https.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.postForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), new TestObject("stuff"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/"), TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getFuture"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        response = httpClient.getForObject(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/getObservable"),
                TestObject.class);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        error = httpClient.postForEntity(new URI("http://localhost:" + properties.get("http.port") + "/stuff/"),
                new TestObject(RandomStringUtils.randomAlphabetic(100)), ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.BAD_REQUEST, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.getBody().code);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/expectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION_HTTP_CODE, error.getStatusCode());
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.code, error.getBody().code);
        Assert.assertEquals(TestRestService.EXPECTED_EXCEPTION.description, error.getBody().description);

        error = httpClient.getForEntity(
                new URI("http://localhost:" + properties.get("http.port") + "/stuff/unexpectedError"),
                ServiceError.class);

        Assert.assertNotNull(response);
        Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, error.getStatusCode());
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.getBody().code);
    } finally {
        context.close();
    }
}

From source file:com.cognitivemedicine.nifi.http.PostHTTP2.java

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 = KeyStore.getInstance(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }//from  w w  w  . j a  v  a 2  s  . c  om
        builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    final String keyFilename = service.getKeyStoreFile();
    if (keyFilename != null) {
        final KeyStore keystore = KeyStore.getInstance(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());
    }

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

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Helper in place to allow us to define out HttpClient SSL context
 *
 * @param ignoreUnverifiedSSL/*from  www.  j a va2s  . c  o  m*/
 * @param credentials
 * @return
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws KeyManagementException
 */
private SSLContext buildSslContext(boolean ignoreUnverifiedSSL, Credentials credentials)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    SSLContextBuilder customContext = SSLContexts.custom();
    if (credentials instanceof CertificateCredentials) {
        customContext = customContext.loadKeyMaterial(((CertificateCredentials) credentials).getKeyStore(),
                ((CertificateCredentials) credentials).getPassword().getPlainText().toCharArray());
    }
    if (ignoreUnverifiedSSL) {
        TrustStrategy easyStrategy = new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        };
        customContext = customContext.loadTrustMaterial(null, easyStrategy);
    }
    return customContext.useTLS().build();
}

From source file:org.openscore.content.httpclient.build.conn.SSLConnectionSocketFactoryBuilder.java

public SSLConnectionSocketFactory build() {
    if (!"true".equalsIgnoreCase(trustAllRootsStr) && !"false".equalsIgnoreCase(trustAllRootsStr)) {
        throw new IllegalArgumentException("'trustAllRoots' can only be 'true' or 'false'");
    }/* w  w  w  . j  a  v  a  2 s.c  om*/
    boolean trustAllRoots = Boolean.parseBoolean(trustAllRootsStr);

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    if (!trustAllRoots) {
        boolean useClientCert = !StringUtils.isEmpty(keystore);
        //validate SSL certificates sent by the server
        boolean useTrustCert = !StringUtils.isEmpty(trustKeystore);

        String javaKeystore = System.getProperty("java.home") + "/lib/security/cacerts";
        boolean storeExists = new File(javaKeystore).exists();

        if (!useClientCert && storeExists) {
            keystore = "file:" + javaKeystore;
            keystorePassword = (StringUtils.isEmpty(keystorePassword)) ? "changeit" : keystorePassword;
            useClientCert = true;
        } else if (useClientCert && !keystore.startsWith("http")) {
            keystore = "file:" + keystore;
        }

        if (!useTrustCert && storeExists) {
            trustKeystore = "file:" + javaKeystore;
            trustPassword = (StringUtils.isEmpty(trustPassword)) ? "changeit" : trustPassword;
            useTrustCert = true;
        } else if (useTrustCert && !trustKeystore.startsWith("http")) {
            trustKeystore = "file:" + trustKeystore;
        }
        createTrustKeystore(sslContextBuilder, useTrustCert);
        //todo client key authentication should not depend on 'trustAllRoots'
        createKeystore(sslContextBuilder, useClientCert);
    } else {
        try {
            //need to override isTrusted() method to accept CA certs because the Apache HTTP Client ver.4.3 will only accepts self-signed certificates
            sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage() + ". " + TRUST_ALL_ROOTS_ERROR + trustAllRoots,
                    e);
        }
    }

    sslContextBuilder.useSSL();
    sslContextBuilder.useTLS();

    SSLConnectionSocketFactory sslsf;
    try {
        String x509HostnameVerifierStr = x509HostnameVerifier.toLowerCase();
        X509HostnameVerifier x509HostnameVerifier = null;
        switch (x509HostnameVerifierStr) {
        case "strict":
            x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
            break;
        case "browser_compatible":
            x509HostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
            break;
        case "allow_all":
            x509HostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            break;
        default:
            x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
        }

        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), x509HostnameVerifier);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage() + ". " + SSL_CONNECTION_ERROR, e);
    }
    return sslsf;
}

From source file:io.cloudslang.content.httpclient.build.conn.SSLConnectionSocketFactoryBuilder.java

public SSLConnectionSocketFactory build() {
    if (!"true".equalsIgnoreCase(trustAllRootsStr) && !"false".equalsIgnoreCase(trustAllRootsStr)) {
        throw new IllegalArgumentException("'trustAllRoots' can only be 'true' or 'false'");
    }/*  w ww  .ja v a2 s  .  co  m*/
    boolean trustAllRoots = Boolean.parseBoolean(trustAllRootsStr);

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    if (!trustAllRoots) {
        boolean useClientCert = !StringUtils.isEmpty(keystore);
        //validate SSL certificates sent by the server
        boolean useTrustCert = !StringUtils.isEmpty(trustKeystore);

        String javaKeystore = System.getProperty("java.home") + "/lib/security/cacerts";
        boolean storeExists = new File(javaKeystore).exists();

        if (!useClientCert && storeExists) {
            keystore = "file:" + javaKeystore;
            keystorePassword = (StringUtils.isEmpty(keystorePassword)) ? "changeit" : keystorePassword;
            useClientCert = true;
        } else if (useClientCert && !keystore.startsWith("http")) {
            keystore = "file:" + keystore;
        }

        if (!useTrustCert && storeExists) {
            trustKeystore = "file:" + javaKeystore;
            trustPassword = (StringUtils.isEmpty(trustPassword)) ? "changeit" : trustPassword;
            useTrustCert = true;
        } else if (useTrustCert && !trustKeystore.startsWith("http")) {
            trustKeystore = "file:" + trustKeystore;
        }
        createTrustKeystore(sslContextBuilder, useTrustCert);
        //todo client key authentication should not depend on 'trustAllRoots'
        createKeystore(sslContextBuilder, useClientCert);
    } else {
        try {
            //need to override isTrusted() method to accept CA certs because the Apache HTTP Client ver.4.3 will only accepts self-signed certificates
            sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage() + ". " + TRUST_ALL_ROOTS_ERROR + trustAllRoots,
                    e);
        }
    }

    sslContextBuilder.useSSL();
    sslContextBuilder.useTLS();

    SSLConnectionSocketFactory sslsf;
    try {
        String x509HostnameVerifierStr = x509HostnameVerifierInputValue.toLowerCase();
        X509HostnameVerifier x509HostnameVerifier;
        switch (x509HostnameVerifierStr) {
        case "strict":
            x509HostnameVerifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;
            break;
        case "browser_compatible":
            x509HostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
            break;
        case "allow_all":
            x509HostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            break;
        default:
            throw new IllegalArgumentException("Invalid value '" + x509HostnameVerifierInputValue
                    + "' for input 'x509HostnameVerifier'. Valid values: 'strict','browser_compatible','allow_all'.");
        }
        // Allow SSLv3, TLSv1, TLSv1.1 and TLSv1.2 protocols only. Client-server communication starts with TLSv1.2 and fallbacks to SSLv3 if needed.
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), SUPPORTED_PROTOCOLS, null,
                x509HostnameVerifier);
    } catch (Exception e) {
        if (e instanceof IllegalArgumentException) {
            throw new IllegalArgumentException(e.getMessage());
        }
        throw new RuntimeException(e.getMessage() + ". " + SSL_CONNECTION_ERROR, e);
    }
    return sslsf;
}

From source file:org.apache.nifi.processors.standard.PostHTTP.java

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());
        }/*from   ww  w  . ja  v  a  2  s . c o m*/
        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());
    }

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

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

From source file:org.eclipse.php.composer.api.packages.AsyncDownloader.java

protected void init() {
    super.init();

    try {//from w ww. j a  v a  2s  .  c  om
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(builder.build());
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", ssf) //$NON-NLS-1$//$NON-NLS-2$
                .build();
        connectionManager = new PoolingHttpClientConnectionManager(r);
    } catch (NoSuchAlgorithmException e) {
        log.error("Exception during init", e); //$NON-NLS-1$
    } catch (KeyManagementException e) {
        log.error("Exception during init", e); //$NON-NLS-1$
    } catch (KeyStoreException e) {
        log.error("Exception during init", e); //$NON-NLS-1$
    }

}