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.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 w ww  .  ja 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;
}

From source file:com.vmware.bdd.security.tls.SimpleSeverTrustTlsSocketFactory.java

/**
 * factory method for custom usage./* w  w w .ja  v a 2 s  .  c  o  m*/
 *
 * @return a factory
 */
public static SSLSocketFactory makeSSLSocketFactory(TrustStoreConfig trustStoreCfg) {
    check(trustStoreCfg);

    SimpleServerTrustManager simpleServerTrustManager = new SimpleServerTrustManager();
    simpleServerTrustManager.setTrustStoreConfig(trustStoreCfg);
    /**
     *  Initialize our own trust manager
     */
    TrustManager[] trustManagers = new TrustManager[] { simpleServerTrustManager };

    SSLContext customSSLContext = null;
    try {
        /**
         * Instantiate a context that implements the family of TLS protocols
         */
        customSSLContext = SSLContext.getInstance("TLS");

        /**
         * Initialize SSL context. Default instances of KeyManager and
         * SecureRandom are used.
         */
        customSSLContext.init(null, trustManagers, null);
    } catch (NoSuchAlgorithmException e) {
        throw new TlsInitException("SSLContext_INIT_ERR", e);
    } catch (KeyManagementException e) {
        throw new TlsInitException("SSLContext_INIT_ERR", e);
    }

    TlsClientConfiguration tlsClientConfiguration = new TlsClientConfiguration();
    /**
     * Build connection configuration and pass to socket
     */
    SSLParameters params = new SSLParameters();
    params.setCipherSuites(tlsClientConfiguration.getCipherSuites());
    params.setProtocols(tlsClientConfiguration.getSslProtocols());
    //      params.setEndpointIdentificationAlgorithm(
    //            config.getEndpointIdentificationAlgorithm());
    /**
     * Use the SSLSocketFactory generated by the SSLContext and wrap it to
     * enable custom cipher suites and protocols
     */
    return new SimpleSeverTrustTlsSocketFactory(customSSLContext.getSocketFactory(), params);
}

From source file:itdelatrisu.opsu.Utils.java

/**
 * Switches validation of SSL certificates on or off by installing a default
 * all-trusting {@link TrustManager}.//from ww w  .  j a  v a  2 s  . c om
 * @param enabled whether to validate SSL certificates
 * @author neu242 (http://stackoverflow.com/a/876785)
 */
public static void setSSLCertValidation(boolean enabled) {
    // create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

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

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

    // install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, enabled ? null : trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
}

From source file:com.subgraph.vega.internal.http.requests.AbstractHttpClientFactory.java

protected static SchemeRegistry createSchemeRegistry() {
    final SchemeRegistry sr = new SchemeRegistry();
    sr.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    SSLContext ctx;
    try {//ww  w  .  j  av a 2  s .  c  om
        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;
            }
        };
        ctx.init(null, new X509TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        sr.register(new Scheme("https", 443, ssf));
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return sr;
}

From source file:org.mahasen.ssl.SSLWrapper.java

/**
 * @param base/*from  w  ww.  ja v a  2 s . com*/
 * @return
 */
public static HttpClient wrapClient(HttpClient base) {

    try {
        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;
            }

        };

        ctx.init(null, new TrustManager[] { tm }, null);

        SSLSocketFactory ssf = new SSLSocketFactory(ctx);

        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_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;

    }

}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * this method utoacepts all certificates in httpsurlconections
 * *///  w  w w.  ja v  a 2  s . com
@SuppressLint("TrulyRandom")
private static void disableSSLCertificateChecking() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }
    } };
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:com.android.volley.toolbox.http.HurlStack.java

public static javax.net.ssl.SSLSocketFactory getSSLSocketFactory() {
    javax.net.ssl.SSLSocketFactory sslSocketFactory = null;
    SSLContext context = null;
    try {/* w  w  w  . j a v  a 2  s  . c o m*/
        // Create an SSLContext that uses our TrustManager
        context = SSLContext.getInstance("TLS");

        TrustManager[] tm = { new JindunX509TrustManager() };

        context.init(null, tm, null);
        sslSocketFactory = context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        //?
        sslSocketFactory = context.getSocketFactory();
    }
    return sslSocketFactory;
}

From source file:com.baidu.qa.service.test.client.SoapReqImpl.java

private static String sendSoapViaHttps(String hosturl, String ip, int port, String action, String method,
        String xml) {/*from  ww  w . ja v  a2 s  .c  o  m*/

    String reqURL = "https://" + ip + ":" + port + action;
    //      Map<String, String> params = null;
    long responseLength = 0; // ?
    String responseContent = null; // ?

    HttpClient httpClient = new DefaultHttpClient(); // httpClient
    httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    X509TrustManager xtm = new X509TrustManager() { // TrustManager
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

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

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    try {
        // TLS1.0SSL3.0??TLSSSL?SSLContext
        SSLContext ctx = SSLContext.getInstance("TLS");

        // TrustManager??TrustManager?SSLSocket
        ctx.init(null, new TrustManager[] { xtm }, null);

        // SSLSocketFactory
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);

        // SchemeRegistrySSLSocketFactoryHttpClient
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme("https", port, socketFactory));

        HttpPost httpPost = new HttpPost(reqURL); // HttpPost

        // add the 3 headers below
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
        httpPost.addHeader("SOAPAction", hosturl + action + method);// SOAP action
        httpPost.addHeader("uuid", "itest");// for editor token of DR-Api

        // HttpEntity requestBody = new
        // ByteArrayEntity(xml.getBytes("UTF-8"));// TODO
        byte[] b = xml.getBytes("UTF-8"); // must be UTF-8
        InputStream is = new ByteArrayInputStream(b, 0, b.length);

        HttpEntity requestBody = new InputStreamEntity(is, b.length,
                ContentType.create("text/xml;charset=UTF-8"));// must be
        // UTF-8
        httpPost.setEntity(requestBody);
        log.info(">> Request URI: " + httpPost.getRequestLine().getUri());

        HttpResponse response = httpClient.execute(httpPost); // POST
        HttpEntity entity = response.getEntity(); // ??

        if (null != entity) {
            responseLength = entity.getContentLength();

            String contentEncoding = null;
            Header ce = response.getEntity().getContentEncoding();
            if (ce != null) {
                contentEncoding = ce.getValue();
            }

            if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
                GZIPInputStream gzipin = new GZIPInputStream(response.getEntity().getContent());
                Scanner in = new Scanner(new InputStreamReader(gzipin, "UTF-8"));
                StringBuilder sb = new StringBuilder();
                while (in.hasNextLine()) {
                    sb.append(in.nextLine()).append(System.getProperty("line.separator"));
                }
                responseContent = sb.toString();
            } else {
                responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

            EntityUtils.consume(entity); // Consume response content
        }
        log.info("?: " + httpPost.getURI());
        log.info("??: " + response.getStatusLine());
        log.info("?: " + responseLength);
        log.info("?: " + responseContent);
    } catch (KeyManagementException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        log.error(e.getMessage(), e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        httpClient.getConnectionManager().shutdown(); // ,?
        return responseContent;
    }
}

From source file:org.mahasen.ssl.WebClientSSLWrapper.java

/**
 * @param base/* w  w  w  . j av a2s.c  om*/
 * @return
 */
public static HttpClient wrapClient(HttpClient base) {

    try {

        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;

            }

        };

        ctx.init(null, new TrustManager[] { tm }, null);

        SSLSocketFactory ssf = new SSLSocketFactory(ctx);

        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_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) {

        System.out.println("Error while configuring security certificate for client");
        return null;

    }

}

From source file:org.elasticsearch.client.RestClientBuilderIntegTests.java

private static SSLContext getSslContext() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    try (InputStream in = RestClientBuilderIntegTests.class.getResourceAsStream("/testks.jks")) {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(in, "password".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, "password".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(keyStore);/*from  w  w  w  .  java  2 s  .  c o m*/
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    }
    return sslContext;
}