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.kuali.mobility.push.factory.iOSConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    SSLSocket socket = null;/*from ww  w. j a v a2 s.c o  m*/
    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);
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:de.betterform.connector.http.ssl.KeyStoreSSLContext.java

private SSLContext createSSLContext() {
    try {/*from   w ww  .  jav  a 2 s .c o  m*/
        TrustManager[] trustmanagers = null;
        KeyManager[] keyManagers = null;
        if (getKeyStoreURL() != null) {
            BetterFORMKeyStoreManager bfkm = new BetterFORMKeyStoreManager();
            bfkm.addCustomX509KeyManager(getKeyStoreURL(), getKeyStorePasswd());
            keyManagers = new KeyManager[] { bfkm };
            BetterFORMTrustManager trustManagers = new BetterFORMTrustManager();
            trustManagers.addCustomX509TrustManager(getKeyStoreURL(), getKeyStorePasswd());
            trustmanagers = trustManagers.getTrustManagers();
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keyManagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOGGER.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOGGER.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:com.qpark.eip.core.spring.security.https.EipHttpsClientHttpRequestFactory.java

/**
 * @see org.springframework.http.client.SimpleClientHttpRequestFactory#prepareConnection(java.net.HttpURLConnection,
 *      java.lang.String)// w w w  .  ja  va 2  s . c  o  m
 */
@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod) {
    try {
        /* Setup HttpsURLConnection. */
        if (HttpsURLConnection.class.isInstance(connection)) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setHostnameVerifier(this.x509TrustManager);
            TrustManager[] trustManagers = new TrustManager[] { this.x509TrustManager };
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagers, new java.security.SecureRandom());
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
        }
        super.prepareConnection(connection, httpMethod);
        /* Setup the basic Authentication. */
        if (HttpURLConnection.class.isInstance(connection) && this.userName != null) {
            HttpURLConnection httpsConnection = connection;
            httpsConnection.setRequestProperty("Authorization",
                    new StringBuffer(128).append("Basic ").append(this.base64UserNamePassword).toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.fineract.module.stellar.fineractadapter.RestAdapterProvider.java

OkHttpClient createClient() {

    final OkHttpClient client = new OkHttpClient();

    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override// ww  w .  j  a  v a2 s  .  c o  m
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ignored) {
    }

    try {
        client.setHostnameVerifier((hostname, session) -> true);
        if (ctx != null) {
            client.setSslSocketFactory(ctx.getSocketFactory());
        }
    } catch (final Exception ignored) {
    }

    return client;
}

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.thrift.ThriftAuthClient.java

public ThriftAuthClient(String serverIP, String remoteServerPort, String webContextRoot)
        throws AuthenticationException {
    try {//from   ww w. j  a  va2 s.co m
        TrustManager easyTrustManager = new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

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

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        //skip host name verification
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(remoteServerPort));

        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getConnectionManager().getSchemeRegistry().register(httpsScheme);

        //If the webContextRoot is null or /
        if (webContextRoot == null || "/".equals(webContextRoot)) {
            //Assign it an empty value since it is part of the thriftServiceURL.
            webContextRoot = "";
        }
        String thriftServiceURL = "https://" + serverIP + ":" + remoteServerPort + webContextRoot + "/"
                + "thriftAuthenticator";
        client = new THttpClient(thriftServiceURL, httpClient);

    } catch (TTransportException e) {
        throw new AuthenticationException("Error in creating thrift authentication client..");
    } catch (Exception e) {
        throw new AuthenticationException("Error in creating thrift authentication client..");
    }
}

From source file:org.jsnap.request.SSLSocketFactory.java

private SSLSocketFactory(boolean trustAll) {
    sf = null;//from   w ww.jav a 2  s  . c o  m
    if (trustAll) {
        // Create a trust manager that does not validate certificate chains.
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, null);
            sf = sc.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            Logger.getLogger(SSLSocketFactory.class).log(Level.WARN, "Unable to instantiate SSLSocketFactory",
                    e);
        } catch (KeyManagementException e) {
            Logger.getLogger(SSLSocketFactory.class).log(Level.WARN, "Unable to instantiate SSLSocketFactory",
                    e);
        }
    } else {
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, null, null);
            sf = sc.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            Logger.getLogger(SSLSocketFactory.class).log(Level.WARN, "Unable to instantiate SSLSocketFactory",
                    e);
        } catch (KeyManagementException e) {
            Logger.getLogger(SSLSocketFactory.class).log(Level.WARN, "Unable to instantiate SSLSocketFactory",
                    e);
        }
    }
}

From source file:org.mifos.tools.provider.RestAdapterProvider.java

private OkHttpClient createClient() {

    final OkHttpClient client = new OkHttpClient();

    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override//from   w  w  w.  j  ava2 s  . c  om
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ex) {
        // do nothing, ignore
    }

    try {
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        };
        client.setHostnameVerifier(hostnameVerifier);
        client.setSslSocketFactory(ctx.getSocketFactory());
    } catch (final Exception e) {
        // do nothing, ignore
    }

    return client;
}

From source file:com.wunding.mlplayer.hudong.DummySSLSocketFactory.java

public DummySSLSocketFactory() {

    try {//  www.  j a  v a 2  s  . c  o m
        SSLContext sslcontent = SSLContext.getInstance("TLS");
        sslcontent.init(null, // KeyManager not required
                new TrustManager[] { new DummyTrustManager() }, null);
        factory = sslcontent.getSocketFactory();

        //            factory = new org.apache.http.conn.ssl.SSLSocketFactory(sslcontent);
        //            // Accept any hostname, so the self-signed certificates don't fail
        //            factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)            
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:com.googlecode.noweco.webmail.httpclient.UnsecureHttpClientFactory.java

public DefaultHttpClient createUnsecureHttpClient(final HttpHost proxy) {
    DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.unregister("https");
    try {//from  w w  w .  j  ava2 s.c o  m
        SSLContext instance = SSLContext.getInstance("TLS");
        TrustManager tm = UnsecureX509TrustManager.INSTANCE;
        instance.init(null, new TrustManager[] { tm }, null);
        schemeRegistry.register(new Scheme("https", 443,
                new SSLSocketFactory(instance, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
    } catch (Exception e) {
        throw new RuntimeException("TLS issue", e);
    }
    httpclient.removeResponseInterceptorByClass(ResponseProcessCookies.class);
    httpclient.addResponseInterceptor(new UnsecureResponseProcessCookies());
    HttpParams params = httpclient.getParams();
    if (proxy != null) {
        ConnRouteParams.setDefaultProxy(params, proxy);
    }
    HttpConnectionParams.setSoTimeout(params, 7000);
    return httpclient;
}

From source file:org.keycloak.truststore.JSSETruststoreConfigurator.java

public javax.net.ssl.SSLSocketFactory getSSLSocketFactory() {
    if (provider == null) {
        return null;
    }//  w  ww.j  a v  a 2 s  .  co m

    if (sslFactory == null) {
        synchronized (this) {
            if (sslFactory == null) {
                try {
                    SSLContext sslctx = SSLContext.getInstance("TLS");
                    sslctx.init(null, getTrustManagers(), null);
                    sslFactory = sslctx.getSocketFactory();
                } catch (Exception e) {
                    throw new RuntimeException("Failed to initialize SSLContext: ", e);
                }
            }
        }
    }
    return sslFactory;
}