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.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }//from  w  w  w  .j  a  va 2s .co  m
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:com.fujitsu.dc.client.http.HttpClientFactory.java

/**
 * This method is used to generate SSLSocket.
 * @return SSLSocket that is generated/*from  w w w  .j  a  v a  2 s .  c o m*/
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public final void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public final void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }

    HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);

    return socketFactory;
}

From source file:com.budrotech.jukebox.service.ssl.SSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keyStorePassword, final SecureRandom random, final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;/*from ww  w.j a  va2s  .c  o m*/
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keystore);

    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    if (trustManagers != null && trustStrategy != null) {
        for (int i = 0; i < trustManagers.length; i++) {
            TrustManager tm = trustManagers[i];

            if (tm instanceof X509TrustManager) {
                trustManagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
            }
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keyManagers, trustManagers, random);

    return sslcontext;
}

From source file:io.personium.client.http.HttpClientFactory.java

/**
 * This method is used to generate SSLSocket.
 * @return SSLSocket that is generated/* w w  w . j a va2  s .c  o  m*/
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public final void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public final void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }

    HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);

    return socketFactory;
}

From source file:com.fujitsu.dc.test.utils.Http.java

static Socket createSocket(URL url) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException {
    String host = url.getHost();/*from   w  ww  .j a va2 s .  c  o m*/
    int port = url.getPort();
    String proto = url.getProtocol();
    if (port < 0) {
        if ("https".equals(proto)) {
            port = PORT_HTTPS;
        }
        if ("http".equals(proto)) {
            port = PORT_HTTP;
        }
    }
    log.debug("sock: " + host + ":" + port);
    log.debug("proto: " + proto);
    // HTTPS?????????????SSLSocket???
    if ("https".equals(proto)) {
        KeyManager[] km = null;
        TrustManager[] tm = { new javax.net.ssl.X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkClientTrusted");
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                log.debug("Insecure SSLSocket Impl for Testing: NOP at X509TrustManager#checkServerTrusted");
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(km, tm, new SecureRandom());
        SocketFactory sf = sslContext.getSocketFactory();
        return (SSLSocket) sf.createSocket(host, port);
    }
    // HTTPS????????
    return new Socket(host, port);
}

From source file:com.createtank.payments.coinbase.RequestClient.java

public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }//from   www  . j a  va2 s .  c om

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

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

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
        //Ignore
    }
}

From source file:com.gson.util.HttpKit.java

/**
 * ?http?/*  ww  w  .j  a  va2s.  c  o  m*/
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    System.setProperty("https.protocols", "SSLv3");
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory  
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:info.guardianproject.netcipher.NetCipher.java

/**
 * Get a {@link TlsOnlySocketFactory} from NetCipher, and specify whether
 * it should use a more compatible, but less strong, suite of ciphers.
 *
 * @see HttpsURLConnection#setDefaultSSLSocketFactory(SSLSocketFactory)
 *//*from w ww . ja  va 2  s . c o m*/
public static TlsOnlySocketFactory getTlsOnlySocketFactory(boolean compatible) {
    SSLContext sslcontext;
    try {
        sslcontext = SSLContext.getInstance("TLSv1");
        sslcontext.init(null, null, null);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyManagementException e) {
        throw new IllegalArgumentException(e);
    }
    return new TlsOnlySocketFactory(sslcontext.getSocketFactory(), compatible);
}

From source file:com.hichengdai.qlqq.front.util.HttpKit.java

/**
 * ?http?// w w  w  . j  a  v a 2 s . co  m
 * 
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java

public static SSLContext createSslContext() throws GeneralSecurityException, IOException {

    // TrustStore
    KeyStore trustStore = FileUtils.loadSslStore(FileUtils.MY_TRUSTSTORE);
    if (trustStore == null)
        throw new IOException("Access denied. Ensure credential storage is available.");
    MyTrustManager myTrustManager = new MyTrustManager(trustStore);
    TrustManager[] tms = new TrustManager[] { myTrustManager };

    // KeyStore//  w ww .  ja v a  2 s. co  m
    KeyManager[] kms = null;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(App.getApp());
    boolean useClientAuth = prefs.getBoolean(App.getApp().getString(R.string.key_client_auth), false);
    if (useClientAuth) {
        KeyStore keyStore = FileUtils.loadSslStore(FileUtils.MY_KEYSTORE);
        if (keyStore == null)
            throw new IOException("Access denied. Ensure credential storage is available.");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, EncryptionUtil.getPassword().toCharArray());
        kms = kmf.getKeyManagers();
    }

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(kms, tms, null);
    return context;
}