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

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

Introduction

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

Prototype

public static SSLContextBuilder create() 

Source Link

Usage

From source file:com.linecorp.armeria.server.thrift.ThriftOverHttp1Test.java

public ThriftOverHttp1Test() {
    try {//w ww . ja  va 2s.c  o m
        SSLContext sslCtx = SSLContextBuilder.create()
                .loadTrustMaterial((TrustStrategy) (chain, authType) -> true).build();

        httpClient = HttpClientBuilder.create().setSSLContext(sslCtx).build();
    } catch (Exception e) {
        throw new Error(e);
    }
}

From source file:com.thoughtworks.go.agent.common.ssl.GoAgentServerHttpClientBuilder.java

public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();// ww w.j  av a2 s .c  o  m
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build())
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create().useProtocol(
            systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT));

    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }

    sslContextBuilder.loadKeyMaterial(agentKeystore(), keystorePassword().toCharArray());

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}

From source file:com.rootcloud.ejb.RootCloudBean.java

private CloseableHttpClient createHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
    HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
    return HttpClients.custom().setSSLSocketFactory(connectionFactory).build();
}

From source file:fi.helsinki.moodi.config.OodiConfig.java

private SSLContext sslContext() {
    String keystoreLocation = environment.getRequiredProperty("httpClient.keystoreLocation");
    String keystorePassword = environment.getRequiredProperty("httpClient.keystorePassword");
    char[] keystorePasswordCharArray = keystorePassword.toCharArray();

    try {/*from w  w w.j  av  a  2  s .  c o m*/
        return SSLContextBuilder.create().loadKeyMaterial(
                oodiKeyStore(keystoreLocation, keystorePasswordCharArray), keystorePasswordCharArray).build();
    } catch (Exception e) {
        throw new RuntimeException("Failed to load client keystore");
    }
}

From source file:com.falcon.orca.actors.Generator.java

public Generator(final ActorRef collector, final String url, final HttpMethods method, final byte[] data,
        final List<Header> headers, final List<Cookie> cookies, final boolean isBodyDynamic,
        final boolean isUrlDynamic, final DynDataStore dataStore)
        throws URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    this.collector = collector;
    this.dataStore = dataStore;
    this.isBodyDynamic = isBodyDynamic;
    this.method = method;
    this.url = url;
    this.headers = headers;
    this.staticRequestData = data != null ? Arrays.copyOf(data, data.length) : new byte[0];

    this.isUrlDynamic = isUrlDynamic;
    CookieStore cookieStore = new BasicCookieStore();
    if (cookies != null) {
        cookies.forEach(cookieStore::addCookie);
    }/*  w ww. ja v  a 2s. co  m*/
    TrustStrategy trustStrategy = (x509Certificates, s) -> true;
    SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(null, trustStrategy).build();
    this.client = HttpClientBuilder.create().setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultCookieStore(cookieStore).build();
}

From source file:io.kamax.mxisd.invitation.InvitationManager.java

@PostConstruct
private void postConstruct() {
    gson = new Gson();

    log.info("Loading saved invites");
    Collection<ThreePidInviteIO> ioList = storage.getInvites();
    ioList.forEach(io -> {/*w  w  w  .  j  a  v a2s  .c  om*/
        log.info("Processing invite {}", gson.toJson(io));
        ThreePidInvite invite = new ThreePidInvite(new MatrixID(io.getSender()), io.getMedium(),
                io.getAddress(), io.getRoomId(), io.getProperties());

        ThreePidInviteReply reply = new ThreePidInviteReply(getId(invite), invite, io.getToken(), "");
        invitations.put(reply.getId(), reply);
    });

    // FIXME export such madness into matrix-java-sdk with a nice wrapper to talk to a homeserver
    try {
        SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
    } catch (Exception e) {
        // FIXME do better...
        throw new RuntimeException(e);
    }

    log.info("Setting up invitation mapping refresh timer");
    refreshTimer = new Timer();
    refreshTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                lookupMappingsForInvites();
            } catch (Throwable t) {
                log.error("Error when running background mapping refresh", t);
            }
        }
    }, 5000L, TimeUnit.MILLISECONDS.convert(cfg.getResolution().getTimer(), TimeUnit.MINUTES));
}

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  ww.  j  av a2 s.c o m*/
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:org.glowroot.central.SyntheticMonitorService.java

SyntheticMonitorService(ActiveAgentDao activeAgentDao, ConfigRepositoryImpl configRepository,
        AlertingDisabledDao alertingDisabledDao, IncidentDao incidentDao, AlertingService alertingService,
        SyntheticResultDao syntheticResponseDao, ClusterManager clusterManager, Ticker ticker, Clock clock,
        String version) throws Exception {
    this.activeAgentDao = activeAgentDao;
    this.configRepository = configRepository;
    this.alertingDisabledDao = alertingDisabledDao;
    this.incidentDao = incidentDao;
    this.alertingService = alertingService;
    this.syntheticResponseDao = syntheticResponseDao;
    this.ticker = ticker;
    this.clock = clock;
    executionRateLimiter = clusterManager.createReplicatedMap("syntheticMonitorExecutionRateLimiter", 30,
            SECONDS);/*  w  w w  .j  a  v a2  s.c o  m*/
    if (version.equals(Version.UNKNOWN_VERSION)) {
        shortVersion = "";
    } else {
        int index = version.indexOf(", built ");
        if (index == -1) {
            shortVersion = "/" + version;
        } else {
            shortVersion = "/" + version.substring(0, index);
        }
    }
    // asyncHttpClient is only used for pings, so safe to ignore cert errors
    asyncHttpClient = HttpAsyncClients.custom().setUserAgent("GlowrootCentral" + shortVersion)
            .setDefaultHeaders(Arrays.asList(new BasicHeader("Glowroot-Transaction-Type", "Synthetic")))
            .setMaxConnPerRoute(10) // increasing from default 2
            .setMaxConnTotal(1000) // increasing from default 20
            .setSSLContext(SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build())
            .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    asyncHttpClient.start();
    syncHttpClientHolder = createSyncHttpClientHolder(shortVersion, configRepository.getHttpProxyConfig());
    // these parameters are from com.machinepublishers.jbrowserdriver.UserAgent.CHROME
    // with added GlowrootCentral/<version> for identification purposes
    userAgent = new UserAgent(Family.WEBKIT, "Google Inc.", "Win32", "Windows NT 6.1",
            "5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                    + " Chrome/45.0.2454.85 Safari/537.36 GlowrootCentral" + shortVersion,
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                    + " Chrome/45.0.2454.85 Safari/537.36 GlowrootCentral" + shortVersion);
    // there is one subworker per worker, so using same max
    subWorkerExecutor = MoreExecutors
            .listeningDecorator(MoreExecutors2.newCachedThreadPool("Synthetic-Monitor-Sub-Worker-%d"));
    workerExecutor = MoreExecutors2.newCachedThreadPool("Synthetic-Monitor-Worker-%d");
    mainLoopExecutor = MoreExecutors2.newSingleThreadExecutor("Synthetic-Monitor-Main-Loop");
    mainLoopExecutor.execute(castInitialized(this));
}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @return a custom scheme registry allowing https connections to servers using
 *         a self-signed certificate/*from   ww w .  ja  v a 2s . c  om*/
 */
private static SchemeRegistry buildTrustSelfSignedSchemeRegistry() {
    /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). 
     * Upgrade only when Solr implementation will become compatible */
    SchemeRegistry registry = null;
    SSLContext sslContext;
    try {
        sslContext = SSLContextBuilder.create().loadTrustMaterial(TrustSelfSignedStrategy.INSTANCE).build();
        registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        registry.register(
                new Scheme("https", 443, new SSLSocketFactory(sslContext, AllowAllHostnameVerifier.INSTANCE)));
    } catch (final Exception e) {
        // Should not happen
        ConcurrentLog.warn("RemoteInstance",
                "Error when initializing SSL context trusting self-signed certificates.", e);
        registry = null;
    }
    return registry;
}

From source file:com.ibm.og.client.ApacheClient.java

private SSLSocketFactory createSSLSocketFactory() {
    final SSLContextBuilder builder = SSLContextBuilder.create();
    configureKeyStores(builder);/*from  w  w w . ja v a 2 s.  c  om*/
    configureTrustStores(builder);
    try {
        return builder.build().getSocketFactory();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}