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.guster.skywebservice.library.webservice.SkyHttp.java

public static void trustAllCertificates(boolean yes) {
    trustAllCertificates = yes;//  w ww.j a  v  a2s  .c  o  m
    if (yes) {
        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());
            sslSocketFactory = sc.getSocketFactory();

        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

private static void trustAllHosts() {

    X509TrustManager easyTrustManager = new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }/*from   ww  w  . j av  a 2s  .  co m*/

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub

        }

    };

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

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");

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

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

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

From source file:it.paolorendano.clm.AbstractCassandraDAO.java

/**
 * Gets the SSL context./* w w w  . j  av  a  2  s  .  co m*/
 *
 * @param truststorePath the truststore path
 * @param truststorePassword the truststore password
 * @param keystorePath the keystore path
 * @param keystorePassword the keystore password
 * @return the SSL context
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws KeyStoreException the key store exception
 * @throws CertificateException the certificate exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws UnrecoverableKeyException the unrecoverable key exception
 * @throws KeyManagementException the key management exception
 */
private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath,
        String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    /* taken from http://www.datastax.com/dev/blog/accessing-secure-dse-clusters-with-cql-native-protocol */

    FileInputStream tsf = new FileInputStream(truststorePath);
    FileInputStream ksf = new FileInputStream(keystorePath);
    SSLContext ctx = SSLContext.getInstance("SSL");

    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(tsf, truststorePassword.toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(ksf, keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keystorePassword.toCharArray());

    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return ctx;
}

From source file:org.wso2.developerstudio.appcloud.utils.client.HttpsJaggeryClient.java

@SuppressWarnings("deprecation")
public static HttpClient wrapClient(HttpClient base, String urlStr) {
    try {/*w w  w .j  av  a2 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 = new ThreadSafeClientConnManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        URL url = new URL(urlStr);
        int port = url.getPort();
        if (port == -1) {
            port = 443;
        }
        String protocol = url.getProtocol();
        if ("https".equals(protocol)) {
            if (port == -1) {
                port = 443;
            }
        } else if ("http".equals(protocol)) {
            if (port == -1) {
                port = 80;
            }
        }
        sr.register(new Scheme(protocol, ssf, port));

        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Throwable ex) {
        ex.printStackTrace();
        log.error("Trust Manager Error", ex);
        return null;
    }
}

From source file:com.gamesalutes.utils.EncryptUtils.java

/**
 * Creates an <code>SSLContext</code> that uses the specified trusted certificates.
 * /*from   w  w  w .  j ava2 s .  co m*/
 * @param protocol the {@link TransportSecurityProtocol} to use for the context
 * @param trustedCerts certificates to import into the <code>SSLContext</code> or <code>null</code>
 *         to accept all issuers
 * @param privateKey the client key to authenticate the client with the server
 * @return the created <code>SSLContext</code>
 * @throws Exception if error occurs during the process of creating the context
 */
public static SSLContext createSSLContext(TransportSecurityProtocol protocol, PrivateKey privateKey,
        java.security.cert.X509Certificate... trustedCerts) throws Exception {
    if (trustedCerts != null && trustedCerts.length == 0)
        throw new IllegalArgumentException("trustedCerts is empty");

    X509TrustManager defaultManager = null;
    KeyManager[] keyManagers = null;
    KeyStore keyStore = null;

    if (privateKey != null || trustedCerts != null) {
        // create a new key store instance that will install the certificates
        // and/or the private keys
        keyStore = KeyStore.getInstance(JKS_TYPE);
        keyStore.load(null, null);
    }

    // import the certs
    if (trustedCerts != null) {
        // set up the key manager for the certificates
        javax.net.ssl.TrustManagerFactory trustFact = javax.net.ssl.TrustManagerFactory
                .getInstance(KEY_MANAGEMENT_ALG_SUN_X509);

        // install the certificates in the key store and give them a unique alias
        int imported = 0;
        for (java.security.cert.X509Certificate cert : trustedCerts) {
            if (cert != null)
                keyStore.setCertificateEntry("cert" + ++imported, cert);
        }
        if (imported == 0)
            throw new IllegalArgumentException("no non-null certs in trustedCerts");
        // add the certs to the trust factory
        trustFact.init(keyStore);

        // get a default trust manager
        TrustManager[] tms = trustFact.getTrustManagers();
        if (tms != null && tms.length >= 1)
            defaultManager = (X509TrustManager) tms[0];
    }

    // import the private key
    if (privateKey != null) {
        keyStore.setKeyEntry("client", privateKey, null, null);
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(privateKey.getAlgorithm());

        kmfactory.init(keyStore, null);
        keyManagers = kmfactory.getKeyManagers();
    }
    //create the SSL context based on these parameters
    SSLContext sslContext = SSLContext.getInstance(protocol.toString());

    // use a CertX509TrustManager since default one will still fail validation for 
    // self-signed certs
    sslContext.init(keyManagers,
            new TrustManager[] { trustedCerts != null ? new CertX509TrustManager(defaultManager, trustedCerts)
                    : new CertX509TrustManager() },
            null);

    return sslContext;

}

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

public static HttpsURLConnection getTrustedConnection(Context context, HttpsURLConnection conn) {
    HttpsURLConnection urlConnection = conn;
    try {/*w  w w.  j a va 2s  . co m*/
        KeyStore localTrustStore;

        localTrustStore = KeyStore.getInstance("BKS");

        InputStream in = context.getResources().openRawResource(R.raw.emm_truststore);

        localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());

        TrustManagerFactory tmf;
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        tmf.init(localTrustStore);

        SSLContext sslCtx;

        sslCtx = SSLContext.getInstance("TLS");

        sslCtx.init(null, tmf.getTrustManagers(), null);

        urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory());
        return urlConnection;
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (CertificateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
        return null;
    }

}

From source file:comsat.sample.tomcat.SampleTomcatTwoConnectorsApplicationTests.java

@BeforeClass
public static void setUp() {
    try {/*from   w w w  . j  ava  2  s .  c o  m*/
        // setup ssl context to ignore certificate errors
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

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

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLContext.setDefault(ctx);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.jboss.as.test.integration.web.security.cert.WebSecurityCERTTestCase.java

public static HttpClient wrapClient(HttpClient base, String alias) {
    try {//from w w w.  ja  v a 2 s . c om
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client-cert");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("security/client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String s, SSLSocket sslSocket) throws IOException {
            }

            @Override
            public void verify(String s, X509Certificate x509Certificate) throws SSLException {
            }

            @Override
            public void verify(String s, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);//SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 8380, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.eclipse.dirigible.ide.common.io.ProxyUtils.java

private static SSLContext createTrustAllSSLContext() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from   w w w . j ava2s  .c  om*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    // Set up a TrustManager that trusts everything
    sslContext.init(null, trustAllCerts, new SecureRandom());
    return sslContext;
}

From source file:com.trsst.Common.java

/**
 * Most trsst nodes run with self-signed certificates, so by default we
 * accept them. While posts are still signed and/or encrypted, a MITM can
 * still refuse our out-going posts and suppress incoming new ones, but this
 * the reason to relay with many trsst servers. Use the -strict option to
 * require CA-signed certificates. Note that nowadays CA-signed certs are no
 * guarantee either./*from   w  w w. j  ava2s .c  om*/
 */
public static void enableAnonymousSSL() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    } };

    SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
        log.error("Can't get SSL context", e);
    } catch (KeyManagementException e) {
        log.error("Can't set SSL socket factory", e);
    }

    // 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);

    // For apache http client
    Protocol anonhttps = new Protocol("https", (ProtocolSocketFactory) new AnonymSSLSocketFactory(), 443); //
    Protocol.registerProtocol("https", anonhttps);
}