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

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

Introduction

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

Prototype

public SSLSocketFactory(final SSLContext sslContext) 

Source Link

Usage

From source file:ui.shared.FreebaseHelper.java

@SuppressWarnings("deprecation")
public static HttpClient wrapClient(HttpClient base) {
    try {/*from  w w  w  . j a  v  a 2  s  .  c  o  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            public boolean verify(String string, SSLSession ssls) {
                return true;
            }

        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.bitrepository.protocol.http.HttpsFileExchange.java

@Override
protected HttpClient getHttpClient() {
    HttpClient client = new DefaultHttpClient();
    try {//from w  ww.j av a 2 s .  c  o  m
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLContext.getDefault());
        Scheme sch = new Scheme("https",
                settings.getReferenceSettings().getFileExchangeSettings().getPort().intValue(), socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Exception e) {
        throw new IllegalStateException("Could not make Https Client.", e);
    }

    return client;
}

From source file:org.openiot.gsn.http.ac.GSNClient.java

public GSNClient(String host, int gsnhttpport, int gsnhttpsport) {
    this.host = host;
    this.gsnhttpport = gsnhttpport;
    this.gsnhttpsport = gsnhttpsport;
    httpclient = new DefaultHttpClient();
    FileInputStream instream = null;
    try {//w w w  .java2 s  .  c o  m
        this.trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        instream = new FileInputStream(new File("conf/clienttestkeystore"));
        this.trustStore.load(instream, "changeit".toCharArray());
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", socketFactory, gsnhttpsport);
        Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(), gsnhttpport);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);

    } catch (KeyStoreException e) {

        logger.error("ERROR IN GSNCLIENT : Exception while creating trustStore :");
        logger.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        logger.error("ERROR IN GSNCLIENT : FileInputStream exception :");
        logger.error(e.getMessage(), e);
    } catch (Exception e) {
        logger.error("ERROR IN GSNCLIENT : Exception while loading truststore :");
        logger.error(e.getMessage(), e);
    } finally {
        try {
            if (instream != null) {
                instream.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:net.openwatch.acluaz.http.AZHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {/*  ww  w  .ja  v a2s .  c  o  m*/
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");
        // Get the raw resource, which contains the keystore with
        // your trusted certificates (root and any intermediate certs)
        InputStream in = context.getResources().openRawResource(R.raw.azkeystore);
        try {
            // Initialize the keystore with the provided trusted certificates
            // Also provide the password of the keystore
            trusted.load(in, SECRETS.SSL_KEYSTORE_PASS.toCharArray());
        } finally {
            in.close();
        }
        // Pass the keystore to the SSLSocketFactory. The factory is responsible
        // for the verification of the server certificate.
        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:org.commonjava.indy.httprox.ProxyHttpsWildcardHostCertTest.java

protected String head(String url, boolean withCACert, String user, String pass) throws Exception {
    CloseableHttpClient client;//ww  w.  ja  v a 2s  .c  om

    if (withCACert) {
        File jks = new File(etcDir, "ssl/ca.jks");
        KeyStore trustStore = getTrustStore(jks);
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        client = proxiedHttp(user, pass, socketFactory);
    } else {
        client = proxiedHttp(user, pass);
    }

    HttpHead req = new HttpHead(url);
    CloseableHttpResponse response = null;

    InputStream stream = null;
    try {
        response = client.execute(req, proxyContext(user, pass));
        /*stream = response.getEntity().getContent();
        final String resulting = IOUtils.toString( stream );
                
        assertThat( resulting, notNullValue() );
        System.out.println( "\n\n>>>>>>>\n\n" + resulting + "\n\n" );*/

        return response.toString();
    } finally {
        IOUtils.closeQuietly(stream);
        HttpResources.cleanupResources(req, response, client);
    }
}

From source file:org.qi4j.library.http.AbstractSecureJettyTest.java

@Before
public void beforeSecure() throws GeneralSecurityException, IOException {
    // Trust HTTP Client
    KeyStore truststore = KeyStore.getInstance("JCEKS");
    truststore.load(new FileInputStream(TRUSTSTORE_FILE), KS_PASSWORD.toCharArray());

    AllowAllHostnameVerifier verifier = new AllowAllHostnameVerifier();

    DefaultHttpClient trustClient = new DefaultHttpClient();
    SSLSocketFactory trustSslFactory = new SSLSocketFactory(truststore);
    trustSslFactory.setHostnameVerifier(verifier);
    SchemeRegistry trustSchemeRegistry = trustClient.getConnectionManager().getSchemeRegistry();
    trustSchemeRegistry.unregister(HTTPS);
    trustSchemeRegistry.register(new Scheme(HTTPS, HTTPS_PORT, trustSslFactory));
    trustHttpClient = trustClient;/*  w ww . j  a va 2 s.c o m*/

    // Mutual HTTP Client
    KeyStore keystore = KeyStore.getInstance("JCEKS");
    keystore.load(new FileInputStream(CLIENT_KEYSTORE_FILE), KS_PASSWORD.toCharArray());

    DefaultHttpClient mutualClient = new DefaultHttpClient();
    SSLSocketFactory mutualSslFactory = new SSLSocketFactory(keystore, KS_PASSWORD, truststore);
    mutualSslFactory.setHostnameVerifier(verifier);
    SchemeRegistry mutualSchemeRegistry = mutualClient.getConnectionManager().getSchemeRegistry();
    mutualSchemeRegistry.unregister(HTTPS);
    mutualSchemeRegistry.register(new Scheme(HTTPS, HTTPS_PORT, mutualSslFactory));
    mutualHttpClient = mutualClient;
}

From source file:com.intel.cosbench.client.http.HttpClientUtil.java

@SuppressWarnings({ "deprecation" })
private static SSLSocketFactory createSSLSocketFactory() {
    try {//from   ww w .  java  2 s . c o m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new X509TrustManager[] { tm }, null);
        String[] enabled = { "SSL_RSA_WITH_NULL_MD5", "SSL_RSA_WITH_NULL_SHA" };
        ctx.createSSLEngine().setEnabledCipherSuites(enabled);

        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        return ssf;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.syncany.connection.plugins.webdav.WebdavConnection.java

private void initSsl() throws Exception {
    this.secure = true;

    /*//w  w w.j a  va2s .c  o m
     * String keyStoreFilename = "/tmp/mystore"; 
     * File keystoreFile = new File(keyStoreFilename); 
     * FileInputStream fis = new
     * FileInputStream(keystoreFile); 
     * KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); // JKS keyStore.load(fis, null);
     */

    TrustStrategy trustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            for (X509Certificate cert : chain) {
                System.out.println(cert);
            }

            // TODO [high] WebDAV SSL: This should query the CLI/GUI (and store the cert. locally); right now, MITMs are easily possible
            return true;
        }
    };

    this.sslSocketFactory = new SSLSocketFactory(trustStrategy);
}

From source file:pl.psnc.synat.wrdz.common.https.HttpsClientHelper.java

/**
 * Gets HTTPS client that can authenticate in WRDZ modules.
 * //from w ww . j a v  a 2s .c o m
 * @param module
 *            module that wants to be authenticated
 * @return HTTPS client
 */
public synchronized HttpClient getHttpsClient(WrdzModule module) {
    DefaultHttpClient httpClient = httpsClients.get(module);
    if (httpClient == null) {
        logger.debug("HTTPS client for module " + module.name() + " is not yet initialized");
        try {
            SSLSocketFactory socketFactory;
            if (config.getHttpsVerifyHostname()) {
                socketFactory = new SSLSocketFactory(new TrustAllStrategy());
            } else {
                socketFactory = new SSLSocketFactory(new TrustAllStrategy(),
                        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            }
            Scheme scheme = new Scheme("https", 443, socketFactory);
            PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
            connectionManager.getSchemeRegistry().register(scheme);

            String cipher = config.getModulesPassword();
            byte[] key = SECRET.getBytes("utf-8");
            Cipher c = Cipher.getInstance("AES");
            SecretKeySpec k = new SecretKeySpec(key, "AES");
            c.init(Cipher.DECRYPT_MODE, k);
            byte[] decrypted = c.doFinal(Base64.decodeBase64(cipher));
            String password = new String(decrypted, "utf-8");
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(module.name(), password);

            httpClient = new DefaultHttpClient(connectionManager);
            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
            httpsClients.put(module, httpClient);
        } catch (Exception e) {
            throw new WrdzRuntimeException(e.getMessage(), e);
        }
    }
    return httpClient;
}

From source file:org.commonjava.indy.httprox.ProxyHttpsTest.java

protected String get(String url, boolean withCACert, String user, String pass) throws Exception {
    CloseableHttpClient client;// w  ww .j  a  va2 s.  c o m

    if (withCACert) {
        File jks = new File(etcDir, "ssl/ca.jks");
        KeyStore trustStore = getTrustStore(jks);
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        client = proxiedHttp(user, pass, socketFactory);
    } else {
        client = proxiedHttp(user, pass);
    }

    HttpGet get = new HttpGet(url);
    CloseableHttpResponse response = null;

    InputStream stream = null;
    try {
        response = client.execute(get, proxyContext(user, pass));
        StatusLine status = response.getStatusLine();
        System.out.println("status >>>> " + status);

        if (status.getStatusCode() == 404) {
            return status.toString();
        }

        stream = response.getEntity().getContent();
        final String resulting = IOUtils.toString(stream);

        assertThat(resulting, notNullValue());
        System.out.println("\n\n>>>>>>>\n\n" + resulting + "\n\n");

        return resulting;
    } finally {
        IOUtils.closeQuietly(stream);
        HttpResources.cleanupResources(get, response, client);
    }
}