Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

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

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final String[] supportedProtocols, final String[] supportedCipherSuites,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.apache.airavata.datacat.agent.dispatcher.MetadataDispatcher.java

private MetadataDispatcher() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    KeyStore trustStore = KeyStore.getInstance("JKS");
    // set up security context
    if (new File("../security/" + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, ""))
            .exists()) {//from  ww w  .j av a  2s.  c o m
        keyStore.load(
                new FileInputStream(new File("../security/"
                        + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, ""))),
                AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray());
    } else {
        ;
        keyStore.load(
                ClassLoader.getSystemResourceAsStream(
                        "security/" + AgentProperties.getInstance().getProperty(Constants.KEYSTORE_FILE, "")),
                AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray());
    }
    if (new File("../security/" + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, ""))
            .exists()) {
        keyStore.load(
                new FileInputStream(new File("../security/"
                        + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, ""))),
                AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_PWD, "").toCharArray());
    } else {
        keyStore.load(
                ClassLoader.getSystemResourceAsStream(
                        "security/" + AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_FILE, "")),
                AgentProperties.getInstance().getProperty(Constants.TRUSTSTORE_PWD, "").toCharArray());
    }
    SSLContext sslContext = SSLContexts.custom()
            .loadKeyMaterial(keyStore,
                    AgentProperties.getInstance().getProperty(Constants.KEYSTORE_PWD, "").toCharArray())
            .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();

    sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    rabbitMQPublisher = new RabbitMQPublisher();
}

From source file:com.aliyun.api.gateway.demo.Client.java

/**
 * <br>/*from  ww w.  jav  a2s  .  com*/
 * Client?httpsURL?keystore?storePasswordkeystore??? 
 * <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html">keytool</a>
 * 
 * @param appKey
 *            APP Key?APIAPP?
 * @param appSecret
 *            APP?APIAPP?
 * @param testEnv
 *            ?truefalse
 */
public Client(String appKey, String appSecret, boolean testEnv) {
    HttpClientBuilder builder = HttpClients.custom();
    try {
        SSLContext sslContext = null;
        if (testEnv) {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    //truetrue
                    return true;
                }
            }).build();
        } else {
            //keytool?keystorekeystore
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            sslContext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
    } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException | CertificateException
            | IOException e) {
        log.error(e.getMessage(), e);
    }
    httpClient = builder.setUserAgent(Constants.USER_AGENT).build();
    this.appKey = appKey;
    this.appSecret = appSecret;
    this.testEnv = testEnv;
}

From source file:org.openhab.binding.ihc.ws.IhcConnectionPool.java

private void init() {

    // Create a local instance of cookie store
    cookieStore = new BasicCookieStore();

    // Create local HTTP context
    localContext = HttpClientContext.create();

    // Bind custom cookie store to the local context
    localContext.setCookieStore(cookieStore);

    httpClientBuilder = HttpClientBuilder.create();

    // Setup a Trust Strategy that allows all certificates.

    logger.debug("Initialize SSL context");

    // Create a trust manager that does not validate certificate chains,
    // but accept all.
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override/* w  ww . j  av a 2 s .  c om*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            logger.trace("Trusting server cert: " + certs[0].getIssuerDN());
        }
    } };

    // Install the all-trusting trust manager

    try {
        // Controller supports only SSLv3 and TLSv1
        sslContext = SSLContext.getInstance("TLSv1");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    } catch (NoSuchAlgorithmException e) {
        logger.warn("Exception", e);
    } catch (KeyManagementException e) {
        logger.warn("Exception", e);
    }

    httpClientBuilder.setSslcontext(sslContext);

    // Controller accepts only HTTPS connections and because normally IP
    // address are used on home network rather than DNS names, create custom
    // host name verifier.
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {

        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            logger.trace("HostnameVerifier: arg0 = " + arg0);
            logger.trace("HostnameVerifier: arg1 = " + arg1);
            return true;
        }
    };

    // Create an SSL Socket Factory, to use our weakened "trust strategy"
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[] { "TLSv1" }, null, hostnameVerifier);

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslSocketFactory).build();

    // Create connection-manager using our Registry. Allows multi-threaded
    // use
    PoolingHttpClientConnectionManager connMngr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

    // Increase max connection counts
    connMngr.setMaxTotal(20);
    connMngr.setDefaultMaxPerRoute(6);

    httpClientBuilder.setConnectionManager(connMngr);
}

From source file:com.mirth.connect.client.core.ServerConnection.java

public ServerConnection(int timeout, String[] httpsProtocols, String[] httpsCipherSuites, boolean allowHTTP) {
    SSLContext sslContext = null;
    try {/*  w ww . j a  va 2  s.  com*/
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        logger.error("Unable to build SSL context.", e);
    }

    String[] enabledProtocols = MirthSSLUtil.getEnabledHttpsProtocols(httpsProtocols);
    String[] enabledCipherSuites = MirthSSLUtil.getEnabledHttpsCipherSuites(httpsCipherSuites);
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            enabledProtocols, enabledCipherSuites, NoopHostnameVerifier.INSTANCE);
    RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory);
    if (allowHTTP) {
        builder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    }
    Registry<ConnectionSocketFactory> socketFactoryRegistry = builder.build();

    PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    httpClientConnectionManager.setDefaultMaxPerRoute(5);
    httpClientConnectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
    // MIRTH-3962: The stale connection settings has been deprecated, and this is recommended instead
    httpClientConnectionManager.setValidateAfterInactivity(5000);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(httpClientConnectionManager);
    HttpUtil.configureClientBuilder(clientBuilder);

    client = clientBuilder.build();
    requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECT_TIMEOUT).setSocketTimeout(timeout).build();
}

From source file:ee.ria.xroad.common.opmonitoring.OpMonitoringDaemonHttpClient.java

private static SSLConnectionSocketFactory createSSLSocketFactory(InternalSSLKey authKey) throws Exception {
    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(getKeyManager(authKey), new TrustManager[] { new OpMonitorTrustManager() }, new SecureRandom());

    return new SSLConnectionSocketFactory(ctx.getSocketFactory(), new String[] { CryptoUtils.SSL_PROTOCOL },
            CryptoUtils.getINCLUDED_CIPHER_SUITES(), NoopHostnameVerifier.INSTANCE);
    // We don't need hostname verification
}

From source file:org.nmdp.b12s.mac.client.http.TextHttpClient.java

private static CloseableHttpClient buildTlsClient(SSLContext sslcontext) {
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    CloseableHttpClient tlsClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    return tlsClient;
}

From source file:cool.pandora.modeller.ModellerClient.java

public static SSLConnectionSocketFactory getSSLFactory() throws CertificateException, NoSuchAlgorithmException,
        KeyStoreException, IOException, KeyManagementException {
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(new File(ModellerClient.class.getResource("/modeller.jks").getFile()),
                    "changeme".toCharArray(), new TrustSelfSignedStrategy())
            .build();/*from w w  w. j a  v a  2s.c om*/
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    return sslsf;
}

From source file:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslClientCert() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();/*from  ww  w.ja v  a 2 s  .  c om*/

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // Server auth against trusted CA root certificate
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    // Client auth
    JpaCa.prepareClientStore(em, "CN=testuser", "./conf/client.pfx", "SuperPassword", "client-cert",
            "./conf/client.cer");
    KeyStore clientStore = KeyStore.getInstance("PKCS12");
    instream = new FileInputStream(new File("./conf/client.pfx"));
    try {
        clientStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore)
            .loadKeyMaterial(clientStore, "SuperPassword".toCharArray()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

/**
 * Creates a custom SSL context where clients will trust own CA and self-signed certificates and associates a HTTP client to the context.
 * @return a HTTP client that will trust own CA and self-signed certificates.
 * @throws Exception if an error occurs.
 *//*from  ww w  . j a  v  a  2 s .  c  o  m*/
private static final CloseableHttpClient createHttpClient(final File trustStoreDir, final char[] password,
        final String url) {
    CloseableHttpClient httpClient = null;
    try {
        final File trustStoreFile = new File(trustStoreDir, "trusted.keystore");
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // create a new, empty trust store
        if (!trustStoreFile.exists()) {
            trustStoreDir.mkdirs();
            trustStoreFile.createNewFile();
            trustStore.load(null, password);

        }
        // import certificate to trust store
        importCertificate(url, trustStore);
        // save trust store to disk
        try (final FileOutputStream outstream = new FileOutputStream(trustStoreFile)) {
            trustStore.store(outstream, password);
        }
        // trust own CA and all self-signed certificates         
        final SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // allow trusted protocols only
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "SSLv2Hello", "TLSv1", "TLSv1.1", "TLSv1.2" }, null,
                new DefaultHostnameVerifier());
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        LOGGER.error("Failed to create HTTP client", e);
    }
    return httpClient;
}