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 javax.net.ssl.SSLSocketFactory socketfactory,
        final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.cgiar.ccafs.ap.util.ClientRepository.java

public DefaultHttpClient verifiedClient(HttpClient base) {
    try {/* w ww.j  a v a  2s.  c  o  m*/
        SSLContext ctx = SSLContext.getInstance("SSL");
        X509TrustManager tm = new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

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

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

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

From source file:com.telefonica.iot.tidoop.apiext.http.HttpClientFactory.java

/**
 * Gets a SchemeRegistry object accepting all the X509 certificates by default.
 * @return A SchemeRegistry object.//from w ww.  j  a  v  a  2 s.com
 */
private SchemeRegistry getSchemeRegistry() {
    // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0

    SSLContext sslContext = null;

    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        logger.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    try {
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            } // getAcceptedIssuers

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            } // getAcceptedIssuers

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } // checkServerTrusted
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    if (sslContext == null) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)");
        return null;
    } // if

    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    return schemeRegistry;
}

From source file:ua.pp.msk.cliqr.PostProcessorImpl.java

private void init(URL url, String user, String password) throws ClientSslException {
    this.targetUrl = url;
    HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());

    BasicAuthCache aCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme(ChallengeState.TARGET);
    aCache.put(htHost, basicAuth);//from   www .  j  av  a 2  s . c o  m

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
    BasicCredentialsProvider cProvider = new BasicCredentialsProvider();
    cProvider.setCredentials(new AuthScope(htHost), creds);
    logger.debug("Credential provider: " + cProvider.toString());

    context = new BasicHttpContext();
    ClientContextConfigurer cliCon = new ClientContextConfigurer(context);
    context.setAttribute(ClientContext.AUTH_CACHE, aCache);
    //context.setAuthCache(aCache);
    cliCon.setCredentialsProvider(cProvider);
    //context.setCredentialsProvider(cProvider);
    SSLSocketFactory sslSocketFactory = null;
    try {
        //SSLContext trustySslContext = SSLContextBuilder.create().loadTrustMaterial( new TrustSelfSignedStrategy()).build();
        //sslConnectionSocketFactory = new SSLConnectionSocketFactory(trustySslContext, new CliQrHostnameVerifier());
        sslSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new CliQrHostnameVerifier());
    } catch (KeyManagementException ex) {
        logger.error("Cannot manage secure keys", ex);
        throw new ClientSslException("Cannot manage secure keys", ex);
    } catch (KeyStoreException ex) {
        logger.error("Cannot build SSL context due to KeyStore error", ex);
        throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex);
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Unsupported security algorithm", ex);
        throw new ClientSslException("Unsupported security algorithm", ex);
    } catch (UnrecoverableKeyException ex) {
        logger.error("Unrecoverable key", ex);
        throw new ClientSslException("Unrecoverrable key", ex);
    }

    DefaultHttpClient defClient = new DefaultHttpClient();
    defClient.setRedirectStrategy(new CliQrRedirectStrategy());
    defClient.setCredentialsProvider(cProvider);
    Scheme https = new Scheme("https", 443, sslSocketFactory);
    defClient.getConnectionManager().getSchemeRegistry().register(https);
    defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy());
    client = defClient;
}

From source file:com.telefonica.iot.cosmos.hive.authprovider.HttpClientFactory.java

/**
 * Gets a SSL SchemeRegistry object accepting all the X509 certificates by default.
 * @return A SSL SchemeRegistry object./*from ww w .j  av a  2 s  .c  o  m*/
 */
private SchemeRegistry getSSLSchemeRegistry() {
    // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0

    SSLContext sslContext;

    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        LOGGER.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")");
        return null;
    } // try catch // try catch

    try {
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            } // getAcceptedIssuers

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            } // getAcceptedIssuers

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } // checkServerTrusted
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        LOGGER.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")");
        return null;
    } // try catch // try catch

    if (sslContext == null) {
        LOGGER.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)");
        return null;
    } // if

    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    return schemeRegistry;
}

From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java

public LDClient(ClientConfiguration config) {
    log.info("Initialising Linked Data Client Service ...");

    this.config = config;

    endpoints = new ArrayList<>();
    for (Endpoint endpoint : defaultEndpoints) {
        endpoints.add(endpoint);//ww  w  . ja v  a  2 s .  c o  m
    }
    endpoints.addAll(config.getEndpoints());

    Collections.sort(endpoints);
    if (log.isInfoEnabled()) {
        for (Endpoint endpoint : endpoints) {
            log.info("- LDClient Endpoint: {}", endpoint.getName());
        }
    }

    providers = new ArrayList<>();
    for (DataProvider provider : defaultProviders) {
        providers.add(provider);
    }
    providers.addAll(config.getProviders());
    if (log.isInfoEnabled()) {
        for (DataProvider provider : providers) {
            log.info("- LDClient Provider: {}", provider.getName());
        }
    }

    retrievalSemaphore = new Semaphore(config.getMaxParallelRequests());

    if (config.getHttpClient() != null) {
        log.debug("Using HttpClient provided in the configuration");
        this.client = config.getHttpClient();
    } else {
        log.debug("Creating default HttpClient based on the configuration");

        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Marmotta LDClient");

        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
        httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

        httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", 443, sf));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(20);
        cm.setDefaultMaxPerRoute(10);

        DefaultHttpClient client = new DefaultHttpClient(cm, httpParams);
        client.setRedirectStrategy(new LMFRedirectStrategy());
        client.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler());
        idleConnectionMonitorThread = new IdleConnectionMonitorThread(client.getConnectionManager());
        idleConnectionMonitorThread.start();

        this.client = client;
    }
}

From source file:org.dataone.proto.trove.net.SocketFactoryManager.java

public SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, UnrecoverableKeyException,
        KeyStoreException, KeyManagementException, CertificateException, IOException {
    // our return object
    log.debug("Enter getSSLSocketFactory");
    SSLSocketFactory socketFactory = null;
    KeyStore keyStore = null;/*w ww .j  ava 2 s. c  om*/

    // get the keystore that will provide the material
    // Catch the exception here so that the TLS connection scheme
    // will still be setup if the client certificate is not found.
    try {
        keyStore = getKeyStore();
    } catch (FileNotFoundException e) {
        // these are somewhat expected for anonymous d1 client use
        log.warn(
                "Could not set up client side authentication - likely because the certificate could not be located: "
                        + e.getMessage());
    }

    // create SSL context
    SSLContext ctx = SSLContext.getInstance("TLS");

    // use a very liberal trust manager for trusting the server
    // TODO: check server trust policy
    X509TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            log.info("checkClientTrusted - " + string);
        }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            log.info("checkServerTrusted - " + string);
        }

        public X509Certificate[] getAcceptedIssuers() {
            log.info("getAcceptedIssuers");
            return null;
        }
    };

    // specify the client key manager
    KeyManager[] keyManagers = { new X509KeyManagerImpl(keyStore, keyStorePassword.toCharArray(), "cilogon") };
    //        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    //        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    //        keyManagers = keyManagerFactory.getKeyManagers();

    // initialize the context
    ctx.init(keyManagers, new TrustManager[] { tm }, new SecureRandom());
    socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    return socketFactory;
}

From source file:net.dataninja.oracle.client.DataNinjaHttpClient.java

private HttpClient getHttpClient()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    // Keep only one copy of the HttpClient
    if (httpClient != null) {
        return httpClient;
    }//from w w  w.  ja v a  2s.  co  m

    // Create a new instance of HTTPClient
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] cert, String authType) throws CertificateException {
            return true;
        }
    };
    SSLSocketFactory factory = new SSLSocketFactory(acceptingTrustStrategy,
            SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 443, factory));
    ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

    httpClient = new DefaultHttpClient(ccm);
    return httpClient;
}

From source file:com.fujitsu.dc.client.http.HttpClientFactory.java

/**
 * This method is used to generate SSLSocket.
 * @return SSLSocket that is generated/*from  w  ww.  j a  v a  2s .  com*/
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public final void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public final void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }

    HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);

    return socketFactory;
}

From source file:io.personium.client.http.HttpClientFactory.java

/**
 * This method is used to generate SSLSocket.
 * @return SSLSocket that is generated/*from   ww  w.j av  a  2 s .  c  om*/
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public final void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public final void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }

    HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);

    return socketFactory;
}