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:org.openntf.xpt.agents.master.ClientSSLResistanceExtender.java

public static HttpClient wrapClient(HttpClient base) {
    try {/*w w  w . java  2s.co  m*/
        SSLContext ctx = SSLContext.getInstance("sslv3");
        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 arg0, SSLSocket arg1) throws IOException {
            }

            public void verify(String arg0, X509Certificate arg1) throws SSLException {
            }

            public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {
            }

            public boolean verify(String hostname, SSLSession session) {
                return true;
            }

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

From source file:eu.prestoprime.p4gui.connection.P4HttpClient.java

public P4HttpClient(String userID) {
    HttpParams params = new BasicHttpParams();

    // setup SSL/*from w w  w. j a v  a 2s . co m*/
    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);

        SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000L);
        SSLSocket socket = (SSLSocket) sf.createSocket(params);
        socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });

        Scheme sch = new Scheme("https", 443, sf);
        this.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (IOException | KeyManagementException | NoSuchAlgorithmException e) {
        logger.error("Unable to create SSL handler for HttpClient...");
        e.printStackTrace();
    }

    // save userID
    this.userID = userID;
}

From source file:com.cloud.network.bigswitch.TrustingProtocolSocketFactory.java

public TrustingProtocolSocketFactory() throws IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*  w  w w. java2s.c o m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // Trust always
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // Trust always
        }
    } };

    try {
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        ssf = sc.getSocketFactory();
    } catch (KeyManagementException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
}

From source file:com.denimgroup.threadfix.remote.AcceptAllTrustManager.java

private SSLContext createAcceptAllSSLContext() {
    try {//w w  w  .  j  a  va  2s.  co m
        AcceptAllTrustManager acceptAllTrustManager = new AcceptAllTrustManager();
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new AcceptAllTrustManager[] { acceptAllTrustManager }, null);
        return context;
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.vmware.bdd.cli.http.HttpClientProvider.java

@Bean(name = SECURE_HTTP_CLIENT)
@Qualifier(SECURE_HTTP_CLIENT)//from  w w w .ja v  a 2 s  .  c o  m
public HttpClient secureHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContext sslContext = SSLContexts.custom().useTLS().build();

    sslContext.init(null, new TrustManager[] { trustManager }, null);

    String[] supportedProtocols = cliProperties.getSupportedProtocols();
    String[] supportedCipherSuites = cliProperties.getSupportedCipherSuites();
    String hostnameVerifier = cliProperties.getHostnameVerifier();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("supported protocols: " + ArrayUtils.toString(supportedProtocols));
        LOGGER.debug("supported cipher suites: " + ArrayUtils.toString(supportedCipherSuites));
        LOGGER.debug("hostname verifier: " + hostnameVerifier);
    }

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols,
            supportedCipherSuites, getHostnameVerifier(hostnameVerifier));

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(20);
    cm.setDefaultMaxPerRoute(10);
    //      HttpHost proxy = new HttpHost("127.0.0.1", 8810, "http");
    //      HttpClient  client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).setProxy(proxy).build();

    HttpClient client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    return client1;
}

From source file:de.undercouch.gradle.tasks.download.internal.DefaultHttpClientFactory.java

private SSLConnectionSocketFactory getInsecureSSLSocketFactory() {
    if (insecureSSLSocketFactory == null) {
        SSLContext sc;
        try {// ww  w.  j av a 2  s.c o  m
            sc = SSLContext.getInstance("SSL");
            sc.init(null, INSECURE_TRUST_MANAGERS, new SecureRandom());
            insecureSSLSocketFactory = new SSLConnectionSocketFactory(sc, INSECURE_HOSTNAME_VERIFIER);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }
    return insecureSSLSocketFactory;
}

From source file:com.thoughtworks.go.server.web.PermissiveSSLSocketFactory.java

private SSLContext getSSLContext() {
    if (this.sslcontext == null) {
        SSLContext context;
        try {/* w  ww  . j  av a2  s .  co m*/
            context = SSLContext.getInstance("SSL");
            context.init(null, new TrustManager[] { new PermissiveX509TrustManager(null) }, null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        this.sslcontext = context;
    }
    return this.sslcontext;
}

From source file:edu.internet2.middleware.subject.provider.LdapPEMSocketFactory.java

protected void initSocketFactory() {
    try {/*from  w ww .  j  a  v  a 2s .  c o m*/
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(keyManagers, trustManagers, new java.security.SecureRandom());
        socketFactory = sc.getSocketFactory();
    } catch (Exception e) {
        log.error("ldap source initSF error: " + e);
    }
}

From source file:org.kuali.mobility.push.factory.iOSFeedbackConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);//from w w w.j a  v  a  2  s .  c  om
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Setup SSL connection./*from w  w w  .j av a 2 s.com*/
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Load custom SSL certificates");
    }

    final SSLContext sslContext;
    try {
        // Load SSL certificates:
        // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
        // Earlier Android versions do not have updated root CA
        // certificates, resulting in connection errors.
        final KeyStore keyStore = loadCertificates(context);

        final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
        final TrustManager[] tms = new TrustManager[] { customTrustManager };

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tms, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}