Example usage for org.apache.http.ssl SSLContextBuilder build

List of usage examples for org.apache.http.ssl SSLContextBuilder build

Introduction

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

Prototype

public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException 

Source Link

Usage

From source file:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClient.java

/**
 * This method creates an insecure SSL factory that will trust on self signed certificates.
 * For that we use {@link TrustSelfSignedStrategy}.
 *///from   ww w  . j a  v  a2 s  . com
protected SSLConnectionSocketFactory createInsecureSslFactory() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(new TrustSelfSignedStrategy());
        return new SSLConnectionSocketFactory(builder.build());
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new ApacheCloudStackClientRuntimeException(e);
    }
}

From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformer.java

/**
 * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds
 *
 * @param keyPair the keypair to generate the csr for
 * @throws IOException if there is a problem during the process
 * @return the resulting certificate chain
 *//*from w  w w  . jav  a  2s . com*/
public X509Certificate[] perform(KeyPair keyPair) throws IOException {
    try {
        List<X509Certificate> certificates = new ArrayList<>();

        HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get();
        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
        sslContextBuilder.useProtocol("TLSv1.2");

        // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory(
                sslContextBuilder.build(), caHostname, certificates));

        String jsonResponseString;
        int responseCode;
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn,
                    domainAlternativeNames, keyPair, signingAlgorithm);
            TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(
                    TlsHelper.calculateHMac(token, request.getPublicKey()),
                    TlsHelper.pemEncodeJcaObject(request));

            HttpPost httpPost = new HttpPost();
            httpPost.setEntity(
                    new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest)));

            if (logger.isInfoEnabled()) {
                logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port);
            }
            try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"),
                    httpPost)) {
                jsonResponseString = IOUtils.toString(
                        new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024),
                        StandardCharsets.UTF_8);
                responseCode = response.getStatusLine().getStatusCode();
            }
        }

        if (responseCode != Response.SC_OK) {
            throw new IOException(
                    RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString);
        }

        if (certificates.size() != 1) {
            throw new IOException(EXPECTED_ONE_CERTIFICATE);
        }

        TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper
                .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class);
        if (!tlsCertificateAuthorityResponse.hasHmac()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC);
        }

        X509Certificate caCertificate = certificates.get(0);
        byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey());

        if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) {
            throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE);
        }

        if (!tlsCertificateAuthorityResponse.hasCertificate()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE);
        }
        X509Certificate x509Certificate = TlsHelper
                .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate()));
        x509Certificate.verify(caCertificate.getPublicKey());
        if (logger.isInfoEnabled()) {
            logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal());
        }
        return new X509Certificate[] { x509Certificate, caCertificate };
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:de.elomagic.maven.http.HTTPMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    try {//  w ww  . jav  a 2  s.  c  o m
        Executor executor;

        if (httpsInsecure) {
            getLog().info("Accepting unsecure HTTPS connections.");
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustAllStrategy());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

                final Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslsf).build();

                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                        sfr);
                connectionManager.setDefaultMaxPerRoute(100);
                connectionManager.setMaxTotal(200);
                connectionManager.setValidateAfterInactivity(1000);

                HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager)
                        .build();

                executor = Executor.newInstance(httpClient);
            } catch (Exception ex) {
                throw new Exception("Unable to setup HTTP client for unstrusted connections.", ex);
            }
        } else {
            executor = Executor.newInstance();
        }

        Settings settings = session.getSettings();
        if (StringUtils.isNotBlank(serverId)) {
            Server server = settings.getServer(serverId);
            if (server == null) {
                throw new Exception("Server ID \"" + serverId + "\" not found in your Maven settings.xml");
            }
            getLog().debug("ServerId: " + serverId);
            executor.auth(server.getUsername(), server.getPassword());
        }

        Request request = createRequestMethod();

        request.setHeader("Accept", accept);

        if (httpHeaders != null) {
            for (Entry<String, String> entry : httpHeaders.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (formParams != null) {
            Form form = Form.form();
            for (Entry<String, String> entry : formParams.entrySet()) {
                form.add(entry.getKey(), entry.getValue());
            }
        }

        if (fromFile != null) {
            if (!fromFile.exists()) {
                throw new MojoExecutionException("From file \"" + fromFile + "\" doesn't exist.");
            }

            if (StringUtils.isBlank(contentType)) {
                contentType = Files.probeContentType(fromFile.toPath());
            }

            getLog().debug("From file: " + fromFile);
            getLog().debug("Upload file size: "
                    + FileUtils.byteCountToDisplaySize(new Long(fromFile.length()).intValue()));
            getLog().debug("Content type: " + contentType);

            if (StringUtils.isBlank(contentType)) {
                request.body(new FileEntity(fromFile));
            } else {
                request.body(new FileEntity(fromFile, ContentType.create(contentType)));
            }
        }

        getLog().info(method + " " + url);

        Response response = executor.execute(request);
        handleResponse(response);
    } catch (Exception ex) {
        getLog().error(ex);
        if (failOnError) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        } else {
            getLog().info("Fail on error is disabled. Continue execution.");
        }
    }

}

From source file:io.confluent.rest.SslTest.java

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;//from  w w w  . j ava  2s  .  c  om
    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" },
                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;
}

From source file:com.buffalokiwi.api.APIHttpClient.java

/**
 * Create a HTTP client that uses a self-signed and always trusted
 * SSL strategy./*from ww w  . j  av a 2 s.  c  o m*/
 *
 * @param custom The client builder
 * @return builder with unsafe SSL strategy
 * @throws APIException If there is a problem creating the client or strategy
 */
private HttpClientBuilder setClientToSelfSigned(final HttpClientBuilder custom) throws APIException {
    final SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(builder.build());
        return custom.setSSLSocketFactory(sf);
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new APIException("Failed to create self-signed trust strategy and/or SSL-enabled HTTP Client", e);
    }
}

From source file:net.maritimecloud.identityregistry.keycloak.spi.eventprovider.McEventListenerProvider.java

private CloseableHttpClient buildHttpClient() {
    KeyStore keyStore = null;/*from   w w  w.j  ava 2  s  . c om*/
    KeyStore trustStore = null;
    FileInputStream instreamKeystore = null;
    FileInputStream instreamTruststore = null;
    try {
        keyStore = KeyStore.getInstance("jks");
        instreamKeystore = new FileInputStream(keystorePath);
        keyStore.load(instreamKeystore, keystorePassword.toCharArray());
        if (truststorePath != null && !truststorePath.isEmpty()) {
            trustStore = KeyStore.getInstance("jks");
            instreamTruststore = new FileInputStream(truststorePath);
            trustStore.load(instreamTruststore, truststorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException e) {
        log.error("Threw exception", e);
        return null;
    } catch (CertificateException e) {
        log.error("Threw exception", e);
        return null;
    } catch (IOException e) {
        log.error("Threw exception", e);
        return null;
    } catch (KeyStoreException e) {
        log.error("Threw exception", e);
        return null;
    } finally {
        try {
            if (instreamKeystore != null) {
                instreamKeystore.close();
            }
            if (instreamTruststore != null) {
                instreamTruststore.close();
            }
        } catch (IOException e) {
            log.error("Threw exception", e);
        }
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext;
    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray());
        // If you have a trust store - should only be needed when the site we contact use self-signed certificates.
        if (trustStore != null) {
            sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        }
        sslContextBuilder.loadKeyMaterial(keyStore, keystorePassword.toCharArray());
        sslcontext = sslContextBuilder.build();
    } catch (KeyManagementException e) {
        log.error("Threw exception", e);
        return null;
    } catch (UnrecoverableKeyException e) {
        log.error("Threw exception", e);
        return null;
    } catch (NoSuchAlgorithmException e) {
        log.error("Threw exception", e);
        return null;
    } catch (KeyStoreException e) {
        log.error("Threw exception", e);
        return null;
    }
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    return httpclient;
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private HttpClientConnectionManager createConnectionManager() throws GeneralSecurityException, IOException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);//from   w  w  w . j a va  2  s  .c  o  m

    if (registry == null) {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
                break;
            }
        }

        X509Certificate[] acceptedIssuers = x509TrustManager.getAcceptedIssuers();
        if (acceptedIssuers != null) {
            // If this is null, something is really wrong...
            int issuerNum = 1;
            for (X509Certificate cert : acceptedIssuers) {
                trustStore.setCertificateEntry("issuer" + issuerNum, cert);
                issuerNum++;
            }
        } else {
            LOG.log(Level.INFO, "Didn't find any new certificates to trust.");
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

        sslContextBuilder.loadTrustMaterial(trustStore,
                new KnownArcGISCertificatesTrustStrategy(new ArrayList<>(trustedCerts)));
        SSLContext sslContext = sslContextBuilder.build();
        SSLContext.setDefault(sslContext);
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new DataStoreProxyHostnameVerifier(new ArrayList<>(trustedCerts)));

        this.registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();
    }
    return new PoolingHttpClientConnectionManager(registry);
}

From source file:org.mycontroller.restclient.core.RestHttpClient.java

private CloseableHttpClient getHttpClientTrustAll() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {/*from ww  w . j a va2  s  .  co  m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        builder.loadTrustMaterial(keyStore, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints)
                    throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                new AnyHostnameVerifier());
        return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(customRequestConfig)
                .build();
    } catch (Exception ex) {
        _logger.error("Exception, ", ex);
        throw new RuntimeException("Unable to create trust ANY http client. Error: " + ex.getMessage());
    }
}