Example usage for javax.net.ssl SSLContext getInstance

List of usage examples for javax.net.ssl SSLContext getInstance

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getInstance.

Prototype

public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SSLContext object that implements the specified secure socket protocol.

Usage

From source file:com.farmafene.commons.cas.HttpClientFactory.java

public DefaultHttpClient getClient() throws IllegalArgumentException {
    DefaultHttpClient httpClient = null;
    URL u = null;/*from   w w w. j  ava2 s.  c  om*/
    try {
        u = new URL(loginURL.toLowerCase());
    } catch (MalformedURLException e) {
        IllegalArgumentException ex = new IllegalArgumentException("Error", e);
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    if ("https".equals(u.getProtocol())) {
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { this }, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            IllegalArgumentException ex = new IllegalArgumentException("Error", e);
            logger.error("Excepcion en el login", ex);
            throw ex;
        } catch (KeyManagementException e) {
            IllegalArgumentException ex = new IllegalArgumentException("Error", e);
            logger.error("Excepcion en el login", ex);
            throw ex;
        }
        SSLSocketFactory sf = new SSLSocketFactory(sslContext, this);
        Scheme httpsScheme = new Scheme("https", u.getPort() == -1 ? HTTPS_DEFAULT_PORT : u.getPort(), sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        Scheme httpScheme = new Scheme("http", HTTP_DEFAULT_PORT, new PlainSocketFactory());
        schemeRegistry.register(httpScheme);

        ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
        httpClient = new DefaultHttpClient(cm);
    } else {
        httpClient = new DefaultHttpClient();
    }
    if (null != proxyHost) {
        if (logger.isDebugEnabled()) {
            logger.debug("Existe proxy: " + this);
        }
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    return httpClient;
}

From source file:com.jwrapper.maven.java.JavaDownloadMojo.java

protected void setupNonVerifingSSL() throws Exception {

    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from  w  ww . j  av  a  2s  . co m*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] arg0, final String arg1)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] arg0, final String arg1)
                throws CertificateException {
        }
    } };

    // Install the all-trusting trust manager
    final SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    final HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(final String hostname, final SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

}

From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java

/**
 * Retrieves certificate chain of specified host:port using https protocol.
 *
 * @param host to get certificate chain from (cannot be null)
 * @param port of host to connect to//from   www .  j ava 2 s  . c  om
 * @return certificate chain
 * @throws Exception Re-thrown from accessing the remote host
 */
public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception {
    checkNotNull(host);

    log.info("Retrieving certificate from https://{}:{}", host, port);

    // setup custom connection manager so we can configure SSL to trust-all
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null);
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory())
            .register(HttpSchemes.HTTPS, sslSocketFactory).build();
    final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);

    try {
        final AtomicReference<Certificate[]> certificates = new AtomicReference<>();

        HttpClient httpClient = httpClientManager.create(new Customizer() {
            @Override
            public void customize(final HttpClientPlan plan) {
                // replace connection-manager with customized version needed to fetch SSL certificates
                plan.getClient().setConnectionManager(connectionManager);

                // add interceptor to grab peer-certificates
                plan.getClient().addInterceptorFirst(new HttpResponseInterceptor() {
                    @Override
                    public void process(final HttpResponse response, final HttpContext context)
                            throws HttpException, IOException {
                        ManagedHttpClientConnection connection = HttpCoreContext.adapt(context)
                                .getConnection(ManagedHttpClientConnection.class);

                        // grab the peer-certificates from the session
                        if (connection != null) {
                            SSLSession session = connection.getSSLSession();
                            if (session != null) {
                                certificates.set(session.getPeerCertificates());
                            }
                        }
                    }
                });
            }
        });

        httpClient.execute(new HttpGet("https://" + host + ":" + port));

        return certificates.get();
    } finally {
        // shutdown single-use connection manager
        connectionManager.shutdown();
    }
}

From source file:org.eclipse.lyo.client.oauth.sample.OAuthClient.java

private static void disableCertificateValidatation(HttpClient client) {
    try {//from  ww w.  j a  va  2  s.  c  om
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } }, new java.security.SecureRandom());
        final SSLSocketFactory socketFactory = new SSLSocketFactory(sc, 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;
            }
        });
        final Scheme https = new Scheme("https", 443, socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(https);
    } catch (GeneralSecurityException e) {
    }
}

From source file:majordodo.client.http.Client.java

private void createClient() {

    try {/* w w  w.  ja  v a 2s. co  m*/
        SSLContext sslContext;
        SSLConnectionSocketFactory sslsf;
        if (configuration.isDisableHttpsVerification()) {
            sslContext = SSLContext.getInstance("SSL");
            TrustManager mytm[] = { new MyTrustManager() };
            sslContext.init(null, mytm, null);
            sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } else {
            sslContext = SSLContexts.custom().build();
            sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        }

        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();

        poolManager = new PoolingHttpClientConnectionManager(r);

        if (configuration.getMaxConnTotal() > 0) {
            poolManager.setMaxTotal(configuration.getMaxConnTotal());
        }
        if (configuration.getMaxConnPerRoute() > 0) {
            poolManager.setDefaultMaxPerRoute(configuration.getMaxConnPerRoute());
        }

        poolManager.setDefaultSocketConfig(SocketConfig.custom().setSoKeepAlive(true).setSoReuseAddress(true)
                .setTcpNoDelay(false).setSoTimeout(configuration.getSotimeout()).build());

        ConnectionKeepAliveStrategy myStrategy = (HttpResponse response, HttpContext context) -> configuration
                .getKeepAlive();

        httpclient = HttpClients.custom().setConnectionManager(poolManager)
                .setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE)
                .setKeepAliveStrategy(myStrategy).build();
    } catch (NoSuchAlgorithmException | KeyManagementException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:com.kylinolap.jdbc.util.DefaultSslProtocolSocketFactory.java

private static SSLContext createEasySSLContext() {
    try {/*from   www . j ava 2  s  . c o  m*/
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new DefaultX509TrustManager(null) }, null);

        return context;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new HttpClientError(e.toString());
    }
}

From source file:com.guster.skywebservice.library.webservice.SkyHttp.java

public static void setSSLCertificate(InputStream certificateFile) throws CertificateException, IOException,
        KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(certificateFile);

    certificateFile.close();/*from w w w  .  j  a v a2 s. c  o  m*/

    // create a keystore containing the certificate
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", cert);

    // create a trust manager for our certificate
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    // create a SSLContext that uses our trust manager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    // set socket factory
    setSSLSocketFactory(context.getSocketFactory());
}

From source file:org.appenders.log4j2.elasticsearch.jest.JKSCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder clientConfigBuilder) {

    try (FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        clientConfigBuilder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        clientConfigBuilder/*ww  w  . j a va2  s  .c  o  m*/
                .httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}