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

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

Introduction

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

Prototype

String TLS

To view the source code for org.apache.http.conn.ssl SSLSocketFactory TLS.

Click Source Link

Usage

From source file:org.zywx.wbpalmstar.platform.certificates.HSSLSocketFactory.java

public HSSLSocketFactory(KeyStore ksP12, String keyPass) throws Exception {
    super(ksP12);
    mSSLContext = SSLContext.getInstance(SSLSocketFactory.TLS);
    KeyManagerFactory kMgrFact = null;
    TrustManager[] tMgrs = null;/*from w  ww .ja v a 2 s  .  com*/
    KeyManager[] kMgrs = null;
    TrustManager tMgr = null;
    tMgr = new HX509TrustManager(ksP12);
    kMgrFact = KeyManagerFactory.getInstance(Http.algorithm);
    if (null != keyPass) {
        kMgrFact.init(ksP12, keyPass.toCharArray());
    } else {
        kMgrFact.init(ksP12, null);
    }
    kMgrs = kMgrFact.getKeyManagers();
    tMgrs = new TrustManager[] { tMgr };
    SecureRandom secureRandom = new java.security.SecureRandom();
    mSSLContext.init(kMgrs, tMgrs, secureRandom);
    if (!Http.isCheckTrustCert()) {
        setHostnameVerifier(new HX509HostnameVerifier());
    } else {
        setHostnameVerifier(STRICT_HOSTNAME_VERIFIER);
    }
}

From source file:org.akita.io._FakeSSLSocketFactory.java

private _FakeSSLSocketFactory() {
    super();//from ww  w . java 2 s  .c om
    TrustManager[] tm = new TrustManager[] { new _FakeX509TrustManager() };
    try {
        this.sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
        this.sslcontext.init(null, tm, new SecureRandom());
        this.socketfactory = this.sslcontext.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
    } catch (KeyManagementException e) {
    }
}

From source file:com.liferay.portal.search.solr.http.SSLSocketFactoryBuilderImpl.java

@Override
public SSLSocketFactory build() throws Exception {
    KeyStore keyStore = _keyStoreLoader.load(_keyStoreType, _keyStorePath, _keyStorePassword);

    if (keyStore == null) {
        if (_log.isDebugEnabled()) {
            _log.debug("Use system defaults because there is no custom key store");
        }/* ww w .j av  a 2  s.c  o  m*/

        return SSLSocketFactory.getSystemSocketFactory();
    }

    KeyStore trustKeyStore = null;

    TrustStrategy trustStrategy = null;

    if (_verifyServerCertificate) {
        trustKeyStore = _keyStoreLoader.load(_trustStoreType, _trustStorePath, _trustStorePassword);

        if (trustKeyStore == null) {
            if (_log.isDebugEnabled()) {
                _log.debug("Use system defaults because there is no custom " + "trust store");
            }

            return SSLSocketFactory.getSystemSocketFactory();
        }
    } else {
        trustStrategy = new TrustSelfSignedStrategy();
    }

    X509HostnameVerifier x509HostnameVerifier = SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;

    if (!_verifyServerHostname) {
        x509HostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    }

    try {
        return new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, String.valueOf(_keyStorePassword),
                trustKeyStore, null, trustStrategy, x509HostnameVerifier);
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(
                    "Use system defaults because the custom SSL socket " + "factory was not able to initialize",
                    e);
        }

        return SSLSocketFactory.getSystemSocketFactory();
    }
}

From source file:org.gege.caldavsyncadapter.caldav.EasySSLSocketFactory.java

private EasySSLSocketFactory() {
    super();//from   w w  w  . ja  va 2s  .  c  o  m
    TrustManager[] tm = new TrustManager[] { new X509TrustManager() {

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

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

    } };
    try {
        this.sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
        this.sslcontext.init(null, tm, new SecureRandom());
        this.socketfactory = this.sslcontext.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Faild to instantiate TrustAllSSLSocketFactory!", e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "Failed to instantiate TrustAllSSLSocketFactory!", e);
    }
}

From source file:org.jasig.portal.security.provider.saml.SSLSecurityImpl.java

public SSLSocketFactory getSSLSocketFactory() {
    try {/*from  w ww.  j av a  2s  . c om*/
        //Implementation taken from SSLSocketFactory constructor with added support for a trust-all
        //trust store if no trustStore is explicitly configured and public keys are available
        KeyManager[] keymanagers = null;
        if (keyStore != null) {
            keymanagers = createKeyManagers(keyStore, keyStorePass);
        }
        TrustManager[] trustmanagers = null;
        if (trustStore != null) {
            trustmanagers = createTrustManagers(trustStore);
        } else if (publicKeys != null) {
            trustmanagers = new TrustManager[] { TrustAllX509TrustManager.INSTANCE };
        }

        final SSLContext sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
        sslcontext.init(keymanagers, trustmanagers, null);

        if (publicKeys != null) {
            return new PublicKeyVerifyingSSLSocketFactory(sslcontext, publicKeys);
        }

        return new SSLSocketFactory(sslcontext);
    } catch (Exception ex) {
        throw new DelegatedAuthenticationRuntimeException(
                "Error dealing with SSL.  See stack trace for details.", ex);
    }
}

From source file:brooklyn.launcher.BrooklynWebServerTest.java

@Test
public void verifyHttps() throws Exception {
    Map<String, ?> flags = ImmutableMap.<String, Object>builder().put("httpsEnabled", true)
            .put("keystoreUrl", getFile("server.ks")).put("keystorePassword", "password").build();
    webServer = new BrooklynWebServer(flags, newManagementContext(brooklynProperties));
    webServer.start();//from   w ww  .j  a  v  a 2  s  .co m

    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password",
                trustStore, (SecureRandom) null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder()
                .port(webServer.getActualPort()).https(true).socketFactory(socketFactory).build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}

From source file:org.apache.brooklyn.launcher.BrooklynWebServerTest.java

@Test(dataProvider = "keystorePaths")
public void verifyHttps(String keystoreUrl) throws Exception {
    Map<String, ?> flags = ImmutableMap.<String, Object>builder().put("httpsEnabled", true)
            .put("keystoreUrl", keystoreUrl).put("keystorePassword", "password").build();
    webServer = new BrooklynWebServer(flags, newManagementContext(brooklynProperties));
    webServer.start();//from w ww . j av  a 2s.c  o m

    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password",
                trustStore, (SecureRandom) null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder()
                .port(webServer.getActualPort()).https(true).socketFactory(socketFactory).build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}

From source file:brooklyn.launcher.BrooklynWebServerTest.java

@Test
public void verifyHttpsFromConfig() throws Exception {
    brooklynProperties.put(BrooklynWebConfig.HTTPS_REQUIRED, true);
    brooklynProperties.put(BrooklynWebConfig.KEYSTORE_URL, getFile("server.ks"));
    brooklynProperties.put(BrooklynWebConfig.KEYSTORE_PASSWORD, "password");
    webServer = new BrooklynWebServer(MutableMap.of(), newManagementContext(brooklynProperties));
    webServer.start();/*from   w w  w  .j a  v  a2  s . c o  m*/

    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password",
                trustStore, (SecureRandom) null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder()
                .port(webServer.getActualPort()).https(true).socketFactory(socketFactory).build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}

From source file:com.cloudbees.eclipse.core.util.Utils.java

/**
 * @param url//from  w  w  w .  ja  va 2s.com
 *          url to connec. Required to determine proxy settings if available. If <code>null</code> then proxy is not
 *          configured for the client returned.
 * @return
 * @throws CloudBeesException
 */
public final static DefaultHttpClient getAPIClient(String url) throws CloudBeesException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

        String version = null;
        if (CloudBeesCorePlugin.getDefault() != null) {
            version = CloudBeesCorePlugin.getDefault().getBundle().getVersion().toString();
        } else {
            version = "n/a";
        }
        HttpProtocolParams.setUserAgent(httpclient.getParams(), "CBEclipseToolkit/" + version);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        CloudBeesCorePlugin plugin = CloudBeesCorePlugin.getDefault();

        URL truststore;

        if (plugin == null) {
            //Outside the OSGI environment, try to open the stream from the current dir.
            truststore = new File("truststore").toURI().toURL();
        } else {
            truststore = plugin.getBundle().getResource("truststore");
        }

        InputStream instream = truststore.openStream();

        try {
            trustStore.load(instream, "123456".toCharArray());
        } finally {
            instream.close();
        }

        TrustStrategy trustAllStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        };

        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustStore,
                null, trustAllStrategy, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        // Override https handling to use provided truststore
        @SuppressWarnings("deprecation")
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        HttpParams params = httpclient.getParams();

        //TODO Make configurable from the UI?
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        if (CloudBeesCorePlugin.getDefault() != null) { // exclude proxy support when running outside eclipse
            IProxyService ps = CloudBeesCorePlugin.getDefault().getProxyService();
            if (ps.isProxiesEnabled()) {

                IProxyData[] pr = ps.select(new URI(url));

                //NOTE! For now we use just the first proxy settings with type HTTP or HTTPS to try out the connection. If configuration has more than 1 conf then for now this likely won't work!
                if (pr != null) {
                    for (int i = 0; i < pr.length; i++) {

                        IProxyData prd = pr[i];

                        if (IProxyData.HTTP_PROXY_TYPE.equals(prd.getType())
                                || IProxyData.HTTPS_PROXY_TYPE.equals(prd.getType())) {

                            String proxyHost = prd.getHost();
                            int proxyPort = prd.getPort();
                            String proxyUser = prd.getUserId();
                            String proxyPass = prd.getPassword();

                            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                            if (prd.isRequiresAuthentication()) {
                                List authpref = new ArrayList();
                                authpref.add(AuthPolicy.BASIC);
                                AuthScope authScope = new AuthScope(proxyHost, proxyPort);
                                httpclient.getCredentialsProvider().setCredentials(authScope,
                                        new UsernamePasswordCredentials(proxyUser, proxyPass));
                            }

                            break;

                        }

                    }
                }
            }
        }

        /*      httpclient.getHostConfiguration().setProxy(proxyHost,proxyPort);      
              //if there are proxy credentials available, set those too
              Credentials proxyCredentials = null;
              String proxyUser = beesClientConfiguration.getProxyUser();
              String proxyPassword = beesClientConfiguration.getProxyPassword();
              if(proxyUser != null || proxyPassword != null)
        proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
              if(proxyCredentials != null)
        client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
                
        */

        return httpclient;

    } catch (Exception e) {
        throw new CloudBeesException("Error while initiating access to JSON APIs!", e);
    }
}

From source file:org.esxx.js.protocol.HTTPHandler.java

private static synchronized ClientConnectionManager getConnectionManager() {
    if (connectionManager == null) {
        SchemeRegistry sr = new SchemeRegistry();
        sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        //      sr.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        try {//from www . j  a v  a 2  s  .  c om
            SSLContext sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
            sslcontext.init(null, new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String auth) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String auth) {
                }
            } }, new java.security.SecureRandom());

            SSLSocketFactory ssf = new SSLSocketFactory(sslcontext, null);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            sr.register(new Scheme("https", ssf, 443));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        connectionManager = new ThreadSafeClientConnManager(getHttpParams(), sr);
    }

    return connectionManager;
}