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:co.cask.cdap.security.server.ExternalMTLSAuthenticationServerTestBase.java

private HttpClient getHTTPClient(KeyManager[] kms, TrustManager[] tms) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(kms, tms, new SecureRandom());
    // only for test purposes ignoring check of certificate hostname matching host on which server runs
    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", getAuthServerPort(), sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    // Apache HttpClient version >4.2 should use BasicClientConnectionManager
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
    return new DefaultHttpClient(cm);
}

From source file:nl.esciencecenter.octopus.webservice.JobLauncherService.java

/**
 * Enable insecure SSL in http client like self signed certificates.
 *
 * @param httpClient/*  ww w .  j  ava  2 s .co  m*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public void useInsecureSSL(HttpClient httpClient)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    SSLSocketFactory socketFactory;
    socketFactory = new SSLSocketFactory(new TrustStrategy() {

        public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy...
            return true;
        }

    }, org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    SchemeRegistry registry = httpClient.getConnectionManager().getSchemeRegistry();
    registry.register(new Scheme("https", 443, socketFactory));
}

From source file:org.jboss.as.test.integration.management.interfaces.HttpManagementInterface.java

private static HttpClient createHttpClient(String host, int port, String username, String password) {
    PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool);
    SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    try {//from   www. j  ava2s.c o  m
        schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, new AllowAllHostnameVerifier())));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true));
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST),
            new UsernamePasswordCredentials(username, password));

    return httpClient;
}

From source file:org.jutge.joc.porra.controller.base.UpdateController.java

private String getUpdateJson() {
    try {//from  w w w. ja v a2 s. com
        // battle-royale.jutge.org has an untrusted cert
        final TrustStrategy easyStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] certificate, final String authType)
                    throws CertificateException {
                return true;
            }
        };
        final SSLSocketFactory socketFactory = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 443, socketFactory));
        final ClientConnectionManager connectionManager = new PoolingClientConnectionManager(registry);
        // Get data
        final HttpClient httpClient = new DefaultHttpClient(connectionManager);
        final HttpGet get = new HttpGet(UPDATE_URL);
        final HttpResponse response = httpClient.execute(get);
        final HttpEntity entity = response.getEntity();
        final String responseBody = EntityUtils.toString(entity);
        return responseBody;
    } catch (Exception exception) {
        this.logger.error(exception.getMessage());
    }
    return null;
}

From source file:io.personium.test.jersey.HttpClientFactory.java

/**
 * SSLSocket?./*w ww  . ja  v  a  2s .  c  om*/
 * @return ???SSLSocket
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    // CHECKSTYLE:OFF
    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 void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

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

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier)
    // hostnameVerifier);

    return socketFactory;
}

From source file:com.fujitsu.dc.test.jersey.HttpClientFactory.java

/**
 * SSLSocket?.// ww  w .j  a va 2 s.co  m
 * @return ???SSLSocket
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    // CHECKSTYLE:OFF
    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);
    }
    // CHECKSTYLE:ON

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier)
    // hostnameVerifier);

    return socketFactory;
}

From source file:cn.ctyun.amazonaws.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/* w ww. j  a v a2 s . c o  m*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    /* Set connection manager */
    ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory
            .createThreadSafeClientConnManager(config, httpClientParams);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams);
    httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        AmazonHttpClient.log
                .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:org.jboss.as.test.integration.web.security.cert.WebSecurityCERTTestCase.java

public static HttpClient wrapClient(HttpClient base, String alias) {
    try {//from w  w  w .j a  v  a  2  s.c o  m
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("security/client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String s, SSLSocket sslSocket) throws IOException {
            }

            @Override
            public void verify(String s, X509Certificate x509Certificate) throws SSLException {
            }

            @Override
            public void verify(String s, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);//SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 8380, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}