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.ibm.sbt.services.util.SSLUtil.java

public static DefaultHttpClient wrapHttpClient(DefaultHttpClient base) {
    try {/*from  w w w. j a va2s .  co m*/
        // Create and assign a dummy TrustManager
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            @Override
            public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);

        // When Apache Client AllowAllHostnameVerifier is strict, this should be used
        // Stays here for reference
        X509HostnameVerifier verifier = new X509HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }

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

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

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

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

From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception {
    final URL url2 = new URL(url);
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(),
            url2.getPort() > 0 ? url2.getPort() : 443);
    socket.setSoTimeout(10000);/*from   ww  w.j  av  a 2 s . c  om*/
    try {
        socket.startHandshake();
        socket.close();
    } catch (SSLException e) {
    }

    final X509Certificate[] chain = trustManager.chain;
    if (chain == null) {
        LOGGER.error("Could not obtain server certificate chain from: " + url);
        return;
    }

    final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    final MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate cert = chain[i];
        final String alias = url2.getHost() + "-" + (i + 1);
        if (!trustStore.containsAlias(alias)) {
            sha1.update(cert.getEncoded());
            md5.update(cert.getEncoded());
            LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN()
                    + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: "
                    + printHexBinary(md5.digest()) + ", Alias: " + alias);
            trustStore.setCertificateEntry(alias, cert);
        }
    }
}

From source file:com.cerema.cloud2.lib.common.network.NetworkUtils.java

public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context)
        throws GeneralSecurityException, IOException {
    if (mAdvancedSslSocketFactory == null) {
        KeyStore trustStore = getKnownServersStore(context);
        AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
        TrustManager[] tms = new TrustManager[] { trustMgr };

        SSLContext sslContext;
        try {/* ww w .ja  v a  2s  .  c  om*/
            sslContext = SSLContext.getInstance("TLSv1.2");
        } catch (NoSuchAlgorithmException e) {
            Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.0");
            sslContext = SSLContext.getInstance("TLSv1");
            // should be available in any device; see reference of supported protocols in 
            // http://developer.android.com/reference/javax/net/ssl/SSLSocket.html
        }
        sslContext.init(null, tms, null);

        mHostnameVerifier = new BrowserCompatHostnameVerifier();
        mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
    }
    return mAdvancedSslSocketFactory;
}

From source file:org.jboss.pnc.auth.keycloakutil.util.HttpUtil.java

public static HttpClient getHttpClient() {
    if (httpClient == null) {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create().useSystemProperties();
        if (sslRequired) {
            if (sslsf != null) {
                clientBuilder.setSSLSocketFactory(sslsf);
            }/*w w w  .  ja  va2 s . com*/
        } else {
            SSLContext sslContext;
            try {
                sslContext = SSLContext.getInstance("SSL");

                // set up a TrustManager that trusts everything
                sslContext.init(null, new TrustManager[] { new X509TrustManager() {

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

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

                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType)
                            throws CertificateException {
                    }
                } }, new SecureRandom());
            } catch (NoSuchAlgorithmException ex) {
                throw new AuthenticationException("Cannot get SSLContext instance for \"SSL\" protocol.", ex);
            } catch (KeyManagementException ex) {
                throw new AuthenticationException("SSLContext initialization failed.", ex);
            }

            clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSSLContext(sslContext);
        }
        httpClient = clientBuilder.build();
    }
    return httpClient;
}

From source file:com.intel.cosbench.client.http.HttpClientUtil.java

@SuppressWarnings({ "deprecation" })
private static SSLSocketFactory createSSLSocketFactory() {
    try {/* w  w  w  . ja v a 2 s .co  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

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

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new X509TrustManager[] { tm }, null);
        String[] enabled = { "SSL_RSA_WITH_NULL_MD5", "SSL_RSA_WITH_NULL_SHA" };
        ctx.createSSLEngine().setEnabledCipherSuites(enabled);

        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        return ssf;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.owncloud.android.lib.common.network.NetworkUtils.java

public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context)
        throws GeneralSecurityException, IOException {
    if (mAdvancedSslSocketFactory == null) {
        KeyStore trustStore = getKnownServersStore(context);
        AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore);
        TrustManager[] tms = new TrustManager[] { trustMgr };

        SSLContext sslContext;
        try {/*ww  w.  j  a va  2  s.c o m*/
            sslContext = SSLContext.getInstance("TLSv1.2");
        } catch (NoSuchAlgorithmException e) {
            Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.0");
            sslContext = SSLContext.getInstance("TLSv1");
            // should be available in any device; see reference of supported protocols in
            // http://developer.android.com/reference/javax/net/ssl/SSLSocket.html
        }
        sslContext.init(null, tms, null);

        mHostnameVerifier = new BrowserCompatHostnameVerifier();
        mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier);
    }
    return mAdvancedSslSocketFactory;
}

From source file:hochschuledarmstadt.photostream_tools.AndroidSocket.java

public static SSLContext createSslContext() throws KeyManagementException, NoSuchAlgorithmException {

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

    TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }//from  w ww  . j  ava2s.co m

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

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

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

    return sslContext;
}

From source file:com.eucalyptus.crypto.util.SslSetup.java

private static SSLContext createServerContext() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext serverContext;
    serverContext = SSLContext.getInstance(PROTOCOL);
    serverContext.init(SslSetup.ServerKeyManager.getKeyManagers(),
            SslSetup.ServerTrustManager.getTrustManagers(), null);
    return serverContext;
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Create SSLContext by given//from   www.  j  a  v  a2s . co m
 * keyStoreUrl,keyStorePassword,trustStoreUrl,trustStorePassword,certAlias
 * 
 * @param keyStoreUrl
 *            the keyStore URL
 * @param keyStorePassword
 *            the keyStore password
 * @param trustStoreUrl
 *            the trustStore URL
 * @param trustStorePassword
 *            the trustStore password
 * @param certAlias
 *            the alias name
 * @return the new SSLContext object
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public static SSLContext createSSLContext(String keyStoreUrl, String keyStorePassword, String trustStoreUrl,
        String trustStorePassword, String certAlias) throws Exception {

    KeyManager[] keymanagers = null;
    TrustManager[] trustmanagers = null;

    KeyStore keystore = getKeyStore(new File(keyStoreUrl).toURL(), keyStorePassword);

    PrivateKey privateKey = (PrivateKey) keystore.getKey(certAlias, keyStorePassword.toCharArray());
    X509Certificate cert = (X509Certificate) keystore.getCertificate(certAlias);

    keymanagers = createKeyManagers(keystore, keyStorePassword);
    for (int i = 0; i < keymanagers.length; i++) {

        if (keymanagers[i] instanceof X509ExtendedKeyManager) {
            keymanagers[i] = new HttpsX509KeyManager((X509ExtendedKeyManager) keymanagers[i], certAlias,
                    privateKey, cert);
        }

    }
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    KeyStore trustStore = getKeyStore(new File(trustStoreUrl).toURL(), trustStorePassword);
    trustmanagers = createTrustManagers(trustStore);
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new HttpsX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    sslcontext.init(keymanagers, trustmanagers, null);

    return sslcontext;
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Builds an SSLConect that trusts the trust material in the KeyStore
 *
 * @param trustMaterial/*from   ww w . j  a  v  a 2s. c  om*/
 * @return
 */
public static SSLContext buildContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);

        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

        ctx = SSLContext.getInstance("TLS");
        ctx.init(keyMgr.getKeyManagers(), tmf.getTrustManagers(), null);
    } catch (KeyStoreException | UnrecoverableKeyException | KeyManagementException
            | NoSuchAlgorithmException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ctx = null;
    }

    return ctx;
}