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.collabnet.tracker.common.httpClient.SslProtocolSocketFactory.java

private SslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {//ww  w. j  a v a 2 s  .  co  m
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            FileInputStream keyStoreInputStream = new FileInputStream(System.getProperty(KEY_STORE));
            keyStore.load(keyStoreInputStream, password);
            keyStoreInputStream.close();
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            log(0, "Could not initialize keystore", e);
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        log(0, "Could not initialize SSL context", e);
    }
}

From source file:edu.mayo.xsltserver.controller.XsltServerController.java

public XsltServerController() {
    super();/*  w  ww.  ja  v a2  s.  co m*/
    try {
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, TRUST_ALL_CERTS, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        this.sslSocketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.xdi.oxauth.service.net.HttpService.java

@Deprecated
public HttpClient getHttpsClientDefaulTrustStore() {
    try {//www.ja  v a 2 s. c om
        PlainSocketFactory psf = PlainSocketFactory.getSocketFactory();

        SSLContext ctx = SSLContext.getInstance("TLS");
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, psf));
        registry.register(new Scheme("https", 443, ssf));

        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        return new DefaultHttpClient(ccm);
    } catch (Exception ex) {
        log.error("Failed to create https client", ex);
        return new DefaultHttpClient();
    }
}

From source file:com.infostretch.volydemo.network.volly.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//from  w ww  . ja v  a 2 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 =
         * MainActivity.getContext().getResources()
         * .openRawResource(R.raw.teststore);
         * 
         * try { trustStore.load(instream, "testpass".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(null, new TrustManager[] { new MyTrustManager(null) }, null);

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

From source file:com.lhtechnologies.DoorApp.AuthenticatorService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();/*from  w w  w .  ja v  a  2  s .c  o  m*/
    } else if (intent.getAction().equals(authenticateAction)) {
        //Check if we want to open the front door or flat door
        String doorToOpen = FrontDoor;
        String authCode = null;
        if (intent.hasExtra(FlatDoor)) {
            doorToOpen = FlatDoor;
            authCode = intent.getCharSequenceExtra(FlatDoor).toString();
        }

        if (intent.hasExtra(LetIn)) {
            doorToOpen = LetIn;
        }

        //Now run the connection code (Hope it runs asynchronously and we do not need AsyncTask --- NOPE --YES
        urlConnection = null;
        URL url;

        //Prepare the return intent
        Intent broadcastIntent = new Intent(AuthenticationFinishedBroadCast);

        try {
            //Try to create the URL, return an error if it fails
            url = new URL(address);

            if (!url.getProtocol().equals("https")) {
                throw new MalformedURLException("Please only use https protocol!");
            }

            String password = "password";
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(getResources().getAssets().open("LH Technologies Root CA.bks"),
                    password.toCharArray());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(keyStore);

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(context.getSocketFactory());
            urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");

            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);

            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());

            //Write our stuff to the output stream;
            out.write("deviceName=" + deviceName + "&udid=" + udid + "&secret=" + secret + "&clientVersion="
                    + clientVersion + "&doorToOpen=" + doorToOpen);
            if (doorToOpen.equals(FlatDoor)) {
                out.write("&authCode=" + authCode);
                //Put an extra in so the return knows we opened the flat door
                broadcastIntent.putExtra(FlatDoor, FlatDoor);
            }

            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            //Read the answer
            String decodedString;
            String returnString = "";
            while ((decodedString = in.readLine()) != null) {
                returnString += decodedString;
            }
            in.close();

            broadcastIntent.putExtra(AuthenticatorReturnCode, returnString);

        } catch (MalformedURLException e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorMalformedURL);
        } catch (Exception e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorUndefined);
            broadcastIntent.putExtra(AuthenticatorErrorDescription, e.getLocalizedMessage());
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
            //Now send a broadcast with the result
            sendOrderedBroadcast(broadcastIntent, null);
            Log.e(this.getClass().getSimpleName(), "Send Broadcast!");
        }
    }

}

From source file:com.sun.identity.proxy.client.ClientHandler.java

/**
 * Returns a new SSL socket factory that does not perform hostname
 * verification.//w w  w .  j  a  v a2  s.c  o m
 *
 * @return the new SSL socket factory.
 */
private static SSLSocketFactory newSSLSocketFactory() {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException nsae) {
        throw new IllegalStateException(nsae); // TODO: handle this better?
    }
    try {
        sslContext.init(null, null, null);
    } catch (KeyManagementException kme) {
        throw new IllegalStateException(kme); // TODO: handle this better?
    }
    SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext);
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return sslSocketFactory;
}

From source file:org.sana.android.net.ssl.SimpleSSLProtocolSocketFactory.java

private static SSLContext createEasySSLContext() throws ClientProtocolException {
    try {//from w  w  w.ja  v  a  2 s  . com
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } }, null);
        return context;
    } catch (Exception e) {
        //LOG.error(e.getMessage(), e);
        throw new ClientProtocolException(e.toString());
    }
}

From source file:com.produban.cloudfoundry.bosh.bosh_javaclient.BoshClientImpl.java

/**
 * This method sets up {@link HttpsURLConnection} so that no certificate or
 * hostname check is performed.//from   www . j a  va2  s. c om
 */
private void disableSSLChecks() {
    try {
        TrustManager trustAllCertificates = new X509TrustManager() {

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

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                // I do nothing because the way to say "OK" is not to throw
                // a CertificateException

            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                // I do nothing because the way to say "OK" is not to throw
                // a CertificateException

            }
        };

        TrustManager[] trustAllCertificatesArray = { trustAllCertificates };
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCertificatesArray, new java.security.SecureRandom());

        HostnameVerifier allHostsValid = new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true; // I always say 'OK'
            }
        };

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new IllegalStateException("Something strange happened here", e);
    }
}

From source file:learn.encryption.ssl.SSLContext_Https.java

public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) {
    if (sslContext != null) {
        return sslContext;
    }/*w ww  .  ja v a  2  s  .co m*/
    try {
        // ??, ??assets
        //InputStream inputStream = App.getInstance().getAssets().open("serverkey.cer");
        InputStream inputStream = new FileInputStream(new File(servercerfile));
        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
        Certificate cer = cerFactory.generateCertificate(inputStream);
        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");//eclipse?jksandroidPKCS12??
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trust", cer);

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        sslContext = SSLContext.getInstance("TLS");

        //?clientKeyStore(android??bks)
        //KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        KeyStore clientKeyStore = KeyStore.getInstance("jks");
        //clientKeyStore.load(App.getInstance().getAssets().open("clientkey.bks"), "123456".toCharArray());
        clientKeyStore.load(new FileInputStream(new File(clientkeyStore)), clientPass.toCharArray());

        // ?clientKeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, clientPass.toCharArray());

        // ?SSLContext  trustManagerFactory.getTrustManagers()
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());//new TrustManager[]{trustManagers}??
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClient(Certificate[] sslCertificate) {
    DefaultHttpClient httpClient;//from   w  ww.  j av a2s  .co m

    httpClient = new DefaultHttpClient();
    try {
        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}