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 String algorithm, final KeyStore keystore, final String keyPassword,
        final KeyStore truststore, final SecureRandom random, final TrustStrategy trustStrategy,
        final X509HostnameVerifier hostnameVerifier)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException 

Source Link

Usage

From source file:com.jt.https.test.send.java

public static String PostTo(String content) {
    String responseMessage = null;
    String filePath = "";
    if (!filePath.endsWith("/")) {
        filePath = filePath + "/";
    }//from   w  w w  .j  a v  a  2  s  .c  om
    HttpClient httpclient = new DefaultHttpClient();
    try {
        KeyStore keystore = KeyStore.getInstance("jks");
        KeyStore trustStore = KeyStore.getInstance("jks");

        FileInputStream keystoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\bis-stg-sdb.jks"));
        FileInputStream trustStoreInstream = new FileInputStream(
                new File("F:\\temp\\?\\lz\\\\EXV_GROUP_BIS_IFRONT_JTLZX_100.jks"));
        //FileInputStream keystoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test.jks"));
        //FileInputStream trustStoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test_trust.jks"));
        try {
            keystore.load(keystoreInstream, "123456".toCharArray());
            trustStore.load(trustStoreInstream, "paic1234".toCharArray());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } finally {
            keystoreInstream.close();
            trustStoreInstream.close();
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.SSL, keystore, "123456",
                trustStore, null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                        return true;
                    }
                }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 8107, socketFactory);

        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpPost post = new HttpPost("https://222.68.184.181:8107");

        StringEntity entity = new StringEntity(content, "text/html", "UTF-8");
        post.setEntity(entity);
        HttpResponse res = httpclient.execute(post);
        HttpEntity resEntity = res.getEntity();
        if (resEntity != null) {
            responseMessage = convertStreamToString(resEntity.getContent());
            System.out.println("???" + content);
            System.out.println("?" + responseMessage);
        }

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return responseMessage;
}

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");
        }/*w  ww . j  a  v a  2 s .c om*/

        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:com.allstate.client.ssl.SSLUtils.java

public static SSLSocketFactory getFactory(Security security) throws GeneralSecurityException {
    X509HostnameVerifier verifier = security.isStrictHostVerification()
            ? SSLSocketFactory.STRICT_HOSTNAME_VERIFIER
            : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(security.getSslContextProtocol(),
            security.getKeyStore(), security.getKeyStorePasswordAsString(), security.getTrustStore(),
            new SecureRandom(), null, verifier);
    return socketFactory;
}

From source file:org.rhq.modules.plugins.wildfly10.SchemeRegistryBuilder.java

public SchemeRegistry buildSchemeRegistry() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (asConnectionParams.isSecure()) {
        SSLSocketFactory sslSocketFactory;
        try {/*from w  ww. ja  v  a2  s . c o m*/
            KeyStore truststore = null;
            if (asConnectionParams.getTruststore() != null) {
                truststore = SecurityUtil.loadKeystore( //
                        asConnectionParams.getTruststoreType(), //
                        asConnectionParams.getTruststore(), //
                        asConnectionParams.getTruststorePassword() //
                );
            }
            KeyStore keystore = null;
            String keyPassword = null;
            if (asConnectionParams.isClientcertAuthentication()) {
                if (asConnectionParams.getKeystore() == null) {
                    keystore = SecurityUtil.loadKeystore( //
                            System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()), //
                            System.getProperty("javax.net.ssl.keyStore"), //
                            System.getProperty("javax.net.ssl.keyStorePassword") //
                    );
                } else {
                    keystore = SecurityUtil.loadKeystore( //
                            asConnectionParams.getKeystoreType(), //
                            asConnectionParams.getKeystore(), //
                            asConnectionParams.getKeystorePassword() //
                    );
                    keyPassword = asConnectionParams.getKeyPassword();
                }
            }
            sslSocketFactory = new SSLSocketFactory(null, keystore, keyPassword, truststore, null,
                    getTrustStrategy(), getHostnameVerifier());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        schemeRegistry.register(
                new Scheme(ASConnection.HTTPS_SCHEME, asConnectionParams.getPort(), sslSocketFactory));
    } else {
        schemeRegistry.register(new Scheme(ASConnection.HTTP_SCHEME, asConnectionParams.getPort(),
                PlainSocketFactory.getSocketFactory()));
    }
    return schemeRegistry;
}

From source file:org.rhq.modules.plugins.jbossas7.SchemeRegistryBuilder.java

public SchemeRegistry buildSchemeRegistry() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (asConnectionParams.isSecure()) {
        SSLSocketFactory sslSocketFactory;
        try {/*from ww w.j  a va 2 s .co m*/
            KeyStore truststore = null;
            if (asConnectionParams.getTruststore() != null) {
                truststore = loadKeystore( //
                        asConnectionParams.getTruststoreType(), //
                        asConnectionParams.getTruststore(), //
                        asConnectionParams.getTruststorePassword() //
                );
            }
            KeyStore keystore = null;
            String keyPassword = null;
            if (asConnectionParams.isClientcertAuthentication()) {
                if (asConnectionParams.getKeystore() == null) {
                    keystore = loadKeystore( //
                            System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()), //
                            System.getProperty("javax.net.ssl.keyStore"), //
                            System.getProperty("javax.net.ssl.keyStorePassword") //
                    );
                } else {
                    keystore = loadKeystore( //
                            asConnectionParams.getKeystoreType(), //
                            asConnectionParams.getKeystore(), //
                            asConnectionParams.getKeystorePassword() //
                    );
                    keyPassword = asConnectionParams.getKeyPassword();
                }
            }
            sslSocketFactory = new SSLSocketFactory(null, keystore, keyPassword, truststore, null,
                    getTrustStrategy(), getHostnameVerifier());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        schemeRegistry.register(new Scheme(HTTPS_SCHEME, asConnectionParams.getPort(), sslSocketFactory));
    } else {
        schemeRegistry.register(
                new Scheme(HTTP_SCHEME, asConnectionParams.getPort(), PlainSocketFactory.getSocketFactory()));
    }
    return schemeRegistry;
}

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

/**
 * @param url//ww w  . j  a v a 2s .c om
 *          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.commonjava.maven.galley.transport.htcli.internal.LocationSSLSocketFactory.java

private synchronized SSLSocketFactory getSSLFactory(final HttpLocation loc) throws IOException {
    //        logger.info( "Finding SSLSocketFactory for repo: {}", repo.getKey() );

    SSLSocketFactory factory = null; // repoFactories.get( repo );
    if (factory == null) {
        KeyStore ks = null;/* ww w . java  2s. co  m*/
        KeyStore ts = null;

        final String kcPem = loc.getKeyCertPem();
        final String kcPass = passwordManager.getPassword(new PasswordEntry(loc, PasswordEntry.KEY_PASSWORD));
        if (kcPem != null) {
            if (kcPass == null || kcPass.length() < 1) {
                logger.error("Invalid configuration. Location: {} cannot have an empty key password!",
                        loc.getUri());
                throw new IOException("Location: " + loc.getUri() + " is misconfigured!");
            }

            try {
                ks = SSLUtils.readKeyAndCert(kcPem, kcPass);

                //                    final StringBuilder sb = new StringBuilder();
                //                    sb.append( "Keystore contains the following certificates:" );
                //
                //                    for ( final Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); )
                //                    {
                //                        final String alias = aliases.nextElement();
                //                        final X509Certificate cert = (X509Certificate) ks.getCertificate( alias );
                //
                //                        if ( cert != null )
                //                        {
                //                            sb.append( "\n" )
                //                              .append( cert.getSubjectDN() );
                //                        }
                //                    }
                //                    sb.append( "\n" );
                //                    logger.info( sb.toString() );
            } catch (final CertificateException e) {
                logger.error(String.format(
                        "Invalid configuration. Location: %s has an invalid client certificate! Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final InvalidKeySpecException e) {
                logger.error(
                        String.format("Invalid configuration. Invalid client key for repository: %s. Error: %s",
                                loc.getUri(), e.getMessage()),
                        e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }

        final String sPem = loc.getServerCertPem();
        //            logger.info( "Server certificate PEM:\n{}", sPem );
        if (sPem != null) {
            try {
                ts = SSLUtils.readCerts(sPem, loc.getHost());

                //                    final StringBuilder sb = new StringBuilder();
                //                    sb.append( "Trust store contains the following certificates:" );
                //
                //                    for ( final Enumeration<String> aliases = ts.aliases(); aliases.hasMoreElements(); )
                //                    {
                //                        final String alias = aliases.nextElement();
                //                        final X509Certificate cert = (X509Certificate) ts.getCertificate( alias );
                //                        if ( cert != null )
                //                        {
                //                            sb.append( "\n" )
                //                              .append( cert.getSubjectDN() );
                //                        }
                //                    }
                //                    sb.append( "\n" );
                //                    logger.info( sb.toString() );
            } catch (final CertificateException e) {
                logger.error(String.format(
                        "Invalid configuration. Location: %s has an invalid server certificate! Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(String.format(
                        "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                        loc.getUri(), e.getMessage()), e);
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }

        if (ks != null || ts != null) {
            try {
                factory = new SSLSocketFactory(SSLSocketFactory.TLS, ks, kcPass, ts, null, null,
                        SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

                // repoFactories.put( repo, factory );
            } catch (final KeyManagementException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final UnrecoverableKeyException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final NoSuchAlgorithmException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            } catch (final KeyStoreException e) {
                logger.error(
                        "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                        e, loc.getUri(), e.getMessage());
                throw new IOException("Failed to initialize SSL connection for repository: " + loc.getUri());
            }
        }
    }

    return factory;
}

From source file:com.redhat.rcm.version.util.InputUtils.java

private static void setupClient() throws VManException {
    if (client == null) {
        SSLSocketFactory sslSocketFactory;
        try {//from  w w  w . ja  v  a2  s  .  c  om
            sslSocketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustKs, null,
                    new TrustSelfSignedStrategy(), SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            //                sslSocketFactory =
            //                    new SSLSocketFactory( SSLSocketFactory.TLS, null, null, trustKs, null, null,
            //                                          SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER );
        } catch (final KeyManagementException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final UnrecoverableKeyException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final NoSuchAlgorithmException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        } catch (final KeyStoreException e) {
            logger.error("Failed to setup SSL socket factory: {}", e, e.getMessage());
            throw new VManException("Failed to setup SSL socket factory: %s", e, e.getMessage());
        }

        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager();
        ccm.getSchemeRegistry().register(new Scheme("https", 443, sslSocketFactory));

        final DefaultHttpClient hc = new DefaultHttpClient(ccm);
        hc.setRedirectStrategy(new DefaultRedirectStrategy());

        final String proxyHost = System.getProperty("http.proxyHost");
        final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1"));

        if (proxyHost != null && proxyPort > 0) {
            final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }

        client = hc;
    }
}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides initializing connection. 
   If is installCert set to true - downloads server certificate and adds to truststore.
 *//*from w w w .  j a  v a2 s.co  m*/
private void init() throws InstallCertException, InitKeystoreException {
    try {
        KeyStore trustStore;
        FileInputStream instream;

        if (installCert) {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InstallCert.install(servername, port, keystorePass);
            instream = new FileInputStream(new File(defKeystoreLocation));
            trustStore.load(instream, keystorePass.toCharArray());
            instream.close();
        } else {
            trustStore = loadJavaDefaultTruststore();
        }

        SSLSocketFactory socketFactory = new SSLSocketFactory(null, null, null, trustStore, null, null,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme(SCHEME_HTTPS, port, socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Exception e) {
        throw new InitKeystoreException();
    }
}