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:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java

/**
 * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the
 * store with the password using {@link KeyStore#load(InputStream,
 * char[])} method.//from ww  w.j  a  v  a 2 s . com
 *
 * @param store The key store holding the certificate details
 * @param alias The alias of the certificate to use
 */
public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(store);

    // Loading the CA certificate from store.
    final Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    AsyncHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Embedded SSL certificate has expired.");
    }

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid.");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid.");
            } else {
                Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates.");
                try {
                    for (X509Certificate cert : chain) {
                        Log.i(LOG_TAG, "Server Certificate Details:");
                        Log.i(LOG_TAG, "---------------------------");
                        Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                        Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                        Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                        Log.i(LOG_TAG, "Version: " + cert.getVersion());
                        Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                        Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                        Log.i(LOG_TAG, "---------------------------");

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's public key chain.
                        cert.verify(rootca.getPublicKey());
                    }
                } catch (InvalidKeyException e) {
                    error = e;
                } catch (NoSuchAlgorithmException e) {
                    error = e;
                } catch (NoSuchProviderException e) {
                    error = e;
                } catch (SignatureException e) {
                    error = e;
                }
            }
            if (null != error) {
                Log.e(LOG_TAG, "Certificate error", error);
                throw new CertificateException(error);
            }
        }

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

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:com.gallery.GalleryRemote.GalleryComm.java

protected GalleryComm(Gallery g, StatusUpdate su) {
    if (g == null) {
        throw new IllegalArgumentException("Must supply a non-null gallery.");
    }/*  w w w.  j  a va 2s .com*/

    this.g = g;
    this.su = su;

    SingleClientConnManager cm = null;

    // Set all-trusting SSL manager, if necessary
    if (g.getUrl().getProtocol().equals("https")) {
        try {
            SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"),
                    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("https", sf, 443));
            cm = new SingleClientConnManager(schemeRegistry);
        } catch (NoSuchAlgorithmException e) {
            Log.logException(Log.LEVEL_CRITICAL, MODULE, e);
        }
    }

    httpclient = new DefaultHttpClient(cm);

    // Use default proxy (as defined by the JVM)
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpclient.setRoutePlanner(routePlanner);

    // use GR User-Agent
    httpclient.removeRequestInterceptorByClass(RequestUserAgent.class);
    final String ua = g.getUserAgent();
    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            request.setHeader(HTTP.USER_AGENT, ua);
        }
    });
}

From source file:com.cloupia.feature.nimble.http.MySSLSocketFactory.java

public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
        throws IOException, UnknownHostException {

    TrustManager[] trustAllCerts = getTrustManager();

    try {//from  w w  w  .j a  v a 2 s . c  o  m

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

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

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        SocketFactory socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        return socketFactory.createSocket(host, port, clientHost, clientPort);

    }

    catch (Exception ex) {

        throw new UnknownHostException("Problems to connect " + host + ex.toString());

    }

}

From source file:org.getcomposer.core.packagist.Downloader.java

private void registerSSLContext(HttpClient client) {

    try {/*from w ww  .  ja v  a 2 s . c  om*/
        X509TrustManager tm = new ComposerTrustManager();
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = client.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    } catch (Exception e) {
        // TODO: handle exception
    }
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.EasySSLProtocolSocketFactory.java

private static SSLContext createEasySSLContext() {
    try {/*from  w  w w  . j av  a 2  s  .  c o m*/
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { (TrustManager) new EasyX509TrustManager(null) },
                new SecureRandom());
        return context;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new HttpClientError(e.toString());
    }
}

From source file:com.michael.openexercise.mc_network.volleydemo.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/*www  .  j av  a2  s. c o  m*/

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = VolleySampleApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = VolleySampleApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:org.kuali.mobility.push.factory.iOSConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    SSLSocket socket = null;//ww  w  .j a v  a  2s .c om
    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:net.bluemix.newsaggregator.api.AuthenticationServlet.java

static public void configureSSL() {
    // note that it's not adviced to use this in a production application
    // you should overwrite the X509TrustManager to use a cacerts file (list of trusted signers) 
    try {/*from   ww w. j a va  2s.c o  m*/
        SSLContext sslContext = SSLContext.getInstance("SSL_TLSv2");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

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

        Executor.unregisterScheme("https");
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Executor.registerScheme(new Scheme("https", 443, sslSocketFactory));

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

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

From source file:org.obm.satellite.client.SatelliteClientModule.java

protected SSLContext buildSSLContext(KeyManager[] keyManagers)
        throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    sslContext.init(keyManagers, trustAllx509Manager(), null);

    return sslContext;
}

From source file:com.longluo.volleydemo.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/* w w w  . j a  v a 2s .  c  om*/

        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = VolleySampleApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = VolleySampleApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}