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:Main.java

public static SSLSocketFactory setCertificates(InputStream... certificates) {
    try {// w  w  w .j  a  va 2s  .c  o  m
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        socketFactory = sslContext.getSocketFactory();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return socketFactory;
}

From source file:Main.java

/**
 * Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to
 * aid testing on a local box, not for use on production.
 *//*from   w ww.java 2  s. c o m*/
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 {
            // Not implemented
        }

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

    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:Main.java

public static String[][] getSpreadSheet(String docId, String tab) {
    try {//from   ww  w.j a  va2  s  .  c om
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

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

            @Override
            public 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();
        //sslSocketFactory.

        // All set up, we can get a resource through https now:
        final URLConnection urlCon = new URL(
                "https://docs.google.com/spreadsheets/d/" + docId + "/export?format=csv&gid=" + tab)
                        .openConnection();
        // Tell the url connection object to use our socket factory which bypasses security checks
        ((HttpsURLConnection) urlCon).setSSLSocketFactory(sslSocketFactory);

        final InputStream input = urlCon.getInputStream();
        BufferedReader r = new BufferedReader(new InputStreamReader(input));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line);
            total.append("\n");
        }

        String theString = total.toString();

        String[][] out = null;

        String rows[] = theString.split("\n");
        out = new String[rows.length][];
        for (int i = 0; i < out.length; i++) {
            String columns[] = rows[i].split(",");
            out[i] = new String[columns.length];
            int corrected = 0;
            for (int j = 0; j < columns.length; j++) {
                if (columns[j].length() > 0 && columns[j].charAt(0) == '"') {
                    out[i][j - corrected] = (columns[j] + ", " + columns[j + 1]).replace("\"", "");
                    j++;
                    corrected += 1;
                } else {
                    out[i][j - corrected] = columns[j];
                }
            }
        }
        return out;

    } catch (final Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 *///from  ww w.  j  av  a 2s. c om
public static SSLSocketFactory newSslSocketFactoryForCa(InputStream certChain) throws Exception {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(new BufferedInputStream(certChain));
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);
    //    ks.setCertificateEntry("ca", cert);

    // Set up trust manager factory to use our key store.
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(ks);
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustManagerFactory.getTrustManagers(), null);
    return context.getSocketFactory();
}

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;/*from w w w.  ja  va2  s.com*/
    try {
        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:Main.java

public static void trustAllHosts(boolean trustAnyCert, boolean trustAnyHost) {
    try {/*from  w w w  . j  ava2 s .co  m*/
        if (trustAnyCert) {
            X509TrustManager easyTrustManager = new X509TrustManager() {

                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };

            // Install the all-trusting trust manager

            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        }

        if (trustAnyHost) {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static SSLContext getDefaultSLLContext() {
    SSLContext sslContext = null;
    try {/* w w  w. j a  v  a2s.c om*/
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManagers }, new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sslContext;
}

From source file:org.apache.stratos.cli.WebClientWrapper.java

public static HttpClient wrapClient(HttpClient base) {
    try {//from w w  w  .  j  av  a 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;
            }
        };
        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) {
        return null;
    }
}

From source file:co.cask.cdap.client.rest.RestUtil.java

public static Registry<ConnectionSocketFactory> getRegistryWithDisabledCertCheck()
        throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override//from w w  w.ja  va 2  s.  com
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }
    } }, new SecureRandom());
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return RegistryBuilder.<ConnectionSocketFactory>create().register("https", sf)
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
}

From source file:org.openntf.xpt.agents.master.ClientSSLResistanceExtender.java

public static HttpClient wrapClient(HttpClient base) {
    try {/* w  ww.j ava2s. c o  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;
    }
}