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.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java

private static SSLContext newNaiveSslContext() {
    try {/*from   w w  w. ja v a2s  . c om*/
        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:com.nesscomputing.tinyhttp.HttpFetcher.java

public HttpFetcher(final SSLConfig sslConfig) {
    params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    registry.register(HTTP_SCHEME);//from   w  w  w.  j ava 2  s.com

    if (sslConfig != null && sslConfig.isSSLEnabled()) {
        try {
            final TrustManager[] trustManagers = new TrustManager[] {
                    HttpsTrustManagerFactory.getTrustManager(sslConfig) };
            final SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, null);
            final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
                    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

            registry.register(new Scheme("https", 443, sslSocketFactory));
            LOG.debug("HTTPS enabled.");
        } catch (GeneralSecurityException ce) {
            throw Throwables.propagate(ce);
        } catch (IOException ioe) {
            throw Throwables.propagate(ioe);
        }
    } else {
        LOG.debug("HTTPS disabled.");
    }

    connectionManager = new SingleClientConnManager(registry);

    LOG.debug("HTTP fetcher ready.");
}

From source file:com.cyberway.issue.crawler.fetcher.HeritrixSSLProtocolSocketFactory.java

/**
 * Shutdown constructor.//from  ww w. j av  a 2  s . c o m
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 */
public HeritrixSSLProtocolSocketFactory()
        throws KeyManagementException, KeyStoreException, NoSuchAlgorithmException {
    // Get an SSL context and initialize it.
    SSLContext context = SSLContext.getInstance("SSL");

    // I tried to get the default KeyManagers but doesn't work unless you
    // point at a physical keystore. Passing null seems to do the right
    // thing so we'll go w/ that.
    context.init(null,
            new TrustManager[] { new ConfigurableX509TrustManager(ConfigurableX509TrustManager.DEFAULT) },
            null);
    this.sslDefaultFactory = context.getSocketFactory();
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

private HttpJsonRequest(Context context) {
    client = new OkHttpClient();

    // set location of the keystore
    MemorizingTrustManager.setKeyStoreFile("private", "sslkeys.bks");

    // register MemorizingTrustManager for HTTPS
    try {//ww  w . j  a  v  a 2s . com
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, MemorizingTrustManager.getInstanceList(context), new java.security.SecureRandom());
        // enables TLSv1.1/1.2 for Jelly Bean Devices
        TLSSocketFactory tlsSocketFactory = new TLSSocketFactory(sc);
        client.setSslSocketFactory(tlsSocketFactory);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    client.setConnectTimeout(10000, TimeUnit.MILLISECONDS);
    client.setReadTimeout(120, TimeUnit.SECONDS);

    // disable hostname verification, when preference is set
    // (this still shows a certification dialog, which requires user interaction!)
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    if (sp.getBoolean(SettingsActivity.CB_DISABLE_HOSTNAME_VERIFICATION_STRING, false))
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    imageClient = client.clone();
    client.interceptors().add(new AuthorizationInterceptor());

    setCredentials(sp.getString(SettingsActivity.EDT_USERNAME_STRING, null),
            sp.getString(SettingsActivity.EDT_PASSWORD_STRING, null),
            sp.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, null));
}

From source file:com.photon.phresco.nativeapp.eshop.net.NetworkManager.java

public static boolean checkHttpsURLStatus(final String url) {
    boolean https_StatusFlag = false;
    System.out.println("Entered in checkHttpsURLStatus >>>>>>>>>>>>>>>");

    URL httpsurl;// w  ww  .  j a  va  2s .co  m
    try {

        // Create a context that doesn't check certificates.
        SSLContext ssl_ctx = SSLContext.getInstance("TLS");
        TrustManager[] trust_mgr = get_trust_mgr();
        ssl_ctx.init(null, // key manager
                trust_mgr, // trust manager
                new SecureRandom()); // random number generator
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory());
        System.out.println("Url =========" + url);
        httpsurl = new URL(url);

        HttpsURLConnection con = (HttpsURLConnection) httpsurl.openConnection();
        con.setHostnameVerifier(DO_NOT_VERIFY);
        int statusCode = con.getResponseCode();
        System.out.println("statusCode =========" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_OK) {

            https_StatusFlag = true;

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return https_StatusFlag;
}

From source file:it_minds.dk.eindberetningmobil_android.server.DebugOkHttpStack.java

private static OkHttpClient getUnsafeOkHttpClient(OkHttpClient client) {
    try {/*from   w w w.  j  av a  2  s .c o  m*/
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        client.setSslSocketFactory(sslSocketFactory);
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return client;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jiubang.core.util.HttpUtils.java

/**
 * Open an URL connection. If HTTPS, accepts any certificate even if not
 * valid, and connects to any host name.
 * //w  ww .  jav a  2s  .  c o m
 * @param url
 *            The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private static URLConnection getConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        // Trust all certificates
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());
        SSLSocketFactory socketFactory = context.getSocketFactory();
        ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);

        // Allow all hostnames
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);

    }
    conn.setConnectTimeout(SOCKET_TIMEOUT);
    conn.setReadTimeout(SOCKET_TIMEOUT);
    return conn;
}

From source file:guru.mmp.common.http.SecureHttpClientBuilder.java

private synchronized SSLConnectionSocketFactory getSSLConnectionSocketFactory() {
    if (sslSocketFactory == null) {
        try {/* w  w w . j a v  a 2  s .  c  o  m*/
            SSLContext sslContext = SSLContext.getInstance("TLS");

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Skip client verification step
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    if (serverValidationEnabled) {
                        // TODO: Implement server certificate validation
                    }
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };

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

            sslSocketFactory = new SSLConnectionSocketFactory(sslContext.getSocketFactory(),
                    new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession sslSession) {
                            if (serverValidationEnabled) {
                                // TODO: Implement proper verification of the server identity -- MARCUS
                            }

                            return true;

                            // if (hostname.equalsIgnoreCase(sslSession.getPeerHost()))
                            // {
                            // return true;
                            // }
                            // else
                            // {
                            // logger.error("Failed to verify the SSL connection to the host ("
                            // + hostname + ") which returned a certificate for the host (" + sslSession.getPeerHost() + ")");
                            //
                            // return false;
                            // }
                        }
                    });
        } catch (Throwable e) {
            throw new RuntimeException("Failed to create the no-trust SSL socket factory", e);
        }
    }

    return sslSocketFactory;
}

From source file:org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory.java

private static SSLContext createEasySSLContext() {
    try {//from  w  w w .ja v a  2 s.  c  om
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
        return context;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new RuntimeException(e.toString());
    }
}

From source file:flex.messaging.services.http.httpclient.EasySSLProtocolSocketFactory.java

private static SSLContext createEasySSLContext() {
    try {//from  ww  w  .ja v  a 2s . com
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null);
        return context;
    } catch (Exception e) {
        if (Trace.ssl) {
            Trace.trace(e.getMessage());
        }
        throw new HttpClientError(e.toString());
    }
}