Example usage for javax.net.ssl SSLContext init

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

Introduction

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

Prototype

public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws KeyManagementException 

Source Link

Document

Initializes this context.

Usage

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 w w w . j  a va 2s . co m*/
 * @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:com.netflix.spinnaker.orca.webhook.config.WebhookConfiguration.java

private SSLSocketFactory getSSLSocketFactory(X509TrustManager trustManager) {
    try {/*from   ww  w . j ava 2  s.co  m*/
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new X509TrustManager[] { trustManager }, null);
        return sslContext.getSocketFactory();
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from  ww  w  .  j a va2s.  c  om*/
        KeyStore keyStore = createKeystore(this.keyStore, this.keyStorePassword);
        KeyManager[] keyManagers = createKeyManagers(keyStore, this.keyPassword);
        KeyStore trustStore = createKeystore(this.trustStore, this.trustStorePassword);
        TrustManager[] trustManagers = createTrustManagers(trustStore);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, new SecureRandom());
        return sslContext;
    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException
            | UnrecoverableKeyException | KeyManagementException ex) {
        LOG.log(Level.SEVERE, ex.getMessage());
        throw new SSLInitializationError(ex.getMessage());
    }
}

From source file:mendhak.teamcity.stash.api.StashClient.java

private HttpURLConnection GetConnection(String targetURL)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URL url = new URL(targetURL);
    if (targetURL.startsWith("http://")) {
        return (HttpURLConnection) url.openConnection();
    }/*from   ww w .  j  a va2s .c o m*/

    //Create an all trusting SSL URL Connection
    //For in-house Stash servers with self-signed certs

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

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

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

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

    return (HttpsURLConnection) url.openConnection();

}

From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java

private SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public void checkClientTrusted(final java.security.cert.X509Certificate[] chain,
                final String authType) {
        }/*from   www .  j av a2 s. c o m*/

        public void checkServerTrusted(final java.security.cert.X509Certificate[] chain,
                final String authType) {
        }

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

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

    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory;
}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private static SSLConnectionSocketFactory getSSLSocketFactory() {
    final TrustManager trustManager = new X509TrustManager() {
        @Override//  w w  w.j  a  v  a2  s .c  om
        public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
        }

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, null);
    } catch (final NoSuchAlgorithmException e) {
        // should not happen
        // e.printStackTrace();
    } catch (final KeyManagementException e) {
        // should not happen
        // e.printStackTrace();
    }

    final SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext,
            new NoopHostnameVerifier());
    return sslSF;
}

From source file:org.opencastproject.kernel.http.impl.HttpClientImpl.java

/**
 * Creates a new client that can deal with all kinds of oddities with regards to http/https connections.
 * //w ww . j  a  va 2  s. co  m
 * @return the client
 */
private DefaultHttpClient makeHttpClient() {

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    try {
        logger.debug("Installing forgiving hostname verifier and trust managers");
        X509TrustManager trustManager = createTrustManager();
        X509HostnameVerifier hostNameVerifier = createHostNameVerifier();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier);
        ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    } catch (KeyManagementException e) {
        logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    }

    return defaultHttpClient;
}

From source file:org.wso2.carbon.databridge.agent.thrift.internal.pool.client.secure.SecureClientPoolFactory.java

@Override
public ThriftSecureEventTransmissionService.Client makeObject(Object key)
        throws AgentSecurityException, TTransportException {
    String[] keyElements = key.toString().split(AgentConstants.SEPARATOR);
    if (keyElements[2].equals(ReceiverConfiguration.Protocol.TCP.toString())) {
        if (params == null) {
            if (trustStore == null) {
                trustStore = System.getProperty("javax.net.ssl.trustStore");
                if (trustStore == null) {
                    throw new AgentSecurityException("No trustStore found");
                }//from  w  w  w.  ja va 2  s .c  o  m
                // trustStore = "/home/suho/projects/wso2/trunk/carbon/distribution/product/modules/distribution/target/wso2carbon-4.0.0-SNAPSHOT/repository/resources/security/client-truststore.jks";
            }

            if (trustStorePassword == null) {
                trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
                if (trustStorePassword == null) {
                    throw new AgentSecurityException("No trustStore password found");
                }
                //trustStorePassword = "wso2carbon";
            }

            params = new TSSLTransportFactory.TSSLTransportParameters();
            params.setTrustStore(trustStore, trustStorePassword);
        }

        String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR);

        TTransport receiverTransport = null;
        try {
            receiverTransport = TSSLTransportFactory.getClientSocket(
                    HostAddressFinder.findAddress(hostNameAndPort[0]), Integer.parseInt(hostNameAndPort[1]), 0,
                    params);
        } catch (SocketException ignored) {
            //already checked
        }

        TProtocol protocol = new TBinaryProtocol(receiverTransport);
        return new ThriftSecureEventTransmissionService.Client(protocol);
    } else {
        try {
            TrustManager easyTrustManager = new X509TrustManager() {
                public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                        throws java.security.cert.CertificateException {
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                        throws java.security.cert.CertificateException {
                }

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslContext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(hostNameAndPort[1]));

            DefaultHttpClient client = new DefaultHttpClient();
            client.getConnectionManager().getSchemeRegistry().register(httpsScheme);

            THttpClient tclient = new THttpClient("https://" + keyElements[3] + "/securedThriftReceiver",
                    client);
            TProtocol protocol = new TCompactProtocol(tclient);
            ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client(
                    protocol);
            tclient.open();
            return authClient;
        } catch (Exception e) {
            throw new AgentSecurityException("Cannot create Secure client for " + keyElements[3], e);
        }
    }
}

From source file:ui.shared.FreebaseHelper.java

@SuppressWarnings("deprecation")
public static HttpClient wrapClient(HttpClient base) {
    try {/*from w ww  . j ava 2  s.c  o m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = 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;
            }

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