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:learn.encryption.ssl.SSLContext_Https.java

/**
 * ??https?.(NoHttp?SecureRandombug)/*from  ww w.j  a va 2  s.c o m*/
 */
public static SSLContext getDefaultSLLContext() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManagers }, new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sslContext;
}

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

private static SSLContext createEasySSLContext() throws IOException {
    try {/*from   w  w  w .  ja  va2  s .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 =
         * 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:io.fabric8.apiman.ApimanStarter.java

private static URL waitForDependency(URL url, String path, String serviceName, String key, String value,
        String username, String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;//  w  ww. j a v a2 s. c o m
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + path);
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH,
                                ApimanStarter.TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(
                                ApimanStarter.CLIENT_KEYSTORE_PATH,
                                ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                    log.info(username + ":" + "*****");
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up. " + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:ee.ria.xroad.proxy.clientproxy.ClientProxy.java

private static SSLConnectionSocketFactory createSSLSocketFactory() throws Exception {
    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(new KeyManager[] { AuthKeyManager.getInstance() }, new TrustManager[] { new AuthTrustManager() },
            new SecureRandom());

    return new FastestConnectionSelectingSSLSocketFactory(ctx, CryptoUtils.getINCLUDED_CIPHER_SUITES());
}

From source file:com.wisdombud.right.client.common.HttpKit.java

private static SSLSocketFactory initSSLSocketFactory() {
    try {//  w  w w . j  av a 2s .  co m
        final TrustManager[] tm = { new HttpKit().new TrustAnyTrustManager() };
        final SSLContext sslContext = SSLContext.getInstance("TLS"); // ("TLS",
        // "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        return sslContext.getSocketFactory();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.netheos.pcsapi.providers.StorageProviderFactory.java

/**
 * Builds a specific HttpClient to certain providers
 *
 * @param providerName// ww  w. j a  v  a 2  s  . co  m
 * @return client to be used, or null if default should be used.
 */
private static HttpClient buildDedicatedHttpClient(String providerName) throws IOException {
    /**
     * Basic java does not trust CloudMe CA CloudMe CA needs to be added
     */
    if (providerName.equals("cloudme") && !PcsUtils.ANDROID) {
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            InputStream is = null;

            try {
                is = StorageProviderFactory.class.getResourceAsStream("/cloudme.jks");
                ks.load(is, "changeit".toCharArray());
            } finally {
                PcsUtils.closeQuietly(is);
            }

            SSLContext context = SSLContext.getInstance("TLS");
            TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            caTrustManagerFactory.init(ks);
            context.init(null, caTrustManagerFactory.getTrustManagers(), null);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(context)));

            ClientConnectionManager cnxManager = new PoolingClientConnectionManager(schemeRegistry);

            return new DefaultHttpClient(cnxManager);

        } catch (GeneralSecurityException ex) {
            throw new UnsupportedOperationException("Can't configure HttpClient for Cloud Me", ex);
        }
    }

    return null;
}

From source file:com.zotoh.maedr.device.HttpIOTrait.java

/**
 * @param createContext/*from   w  ww.  j  av  a2s.c  om*/
 * @param sslType
 * @param key
 * @param pwd
 * @return
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableEntryException
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws IOException
 * @throws KeyManagementException
 */
protected static Tuple cfgSSL(boolean createContext, String sslType, URL key, String pwd)
        throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException, CertificateException,
        IOException, KeyManagementException {

    boolean jks = key.getFile().endsWith(".jks");
    InputStream inp = key.openStream();
    CryptoStore s;

    try {
        s = jks ? new JKSStore() : new PKCSStore();
        s.init(pwd);
        s.addKeyEntity(inp, pwd);
    } finally {
        StreamUte.close(inp);
    }

    SSLContext c = null;
    if (createContext) {
        c = SSLContext.getInstance(sslType);
        c.init(s.getKeyManagerFactory().getKeyManagers(), s.getTrustManagerFactory().getTrustManagers(),
                Crypto.getInstance().getSecureRandom());
    }

    return new Tuple(s, c);
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

protected static SSLContext getCertificateSSLContext() throws GeneralSecurityException {
    SSLContext sslContext = getSSLContext();
    JSONObject sslConf = null;//from w  ww  .j  a v a 2s.c  o m
    try {
        sslConf = readSSLConfToJson();
    } catch (Exception e) {
        LOG.error("readSSLConfToJson error", e);
    }
    sslContext.init(createKeyManager(sslConf), createTrustManager(sslConf), new SecureRandom());
    return sslContext;
}

From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java

private static SSLContext newNaiveSslContext() {
    try {// ww w.j  a v  a  2  s  .  c  o  m
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[] {}, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, new SecureRandom());

        return ctx;
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
}

From source file:helpers.Methods.java

public static void trustAllCertificates() {
    //Certification check
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/* w  w w.  j  av a2  s.  c  o  m*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

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

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

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException ex) {
        Variables.logger.Log(Methods.class, Variables.LogType.Error,
                "Error in trusting all certificates. Details:\r\n" + ex.getMessage());
    }
}