Example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDefaultHostnameVerifier.

Prototype

public static void setDefaultHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the default HostnameVerifier inherited by a new instance of this class.

Usage

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public static void setupSSL(String enpointUrl, boolean sslDebug) {

    if (enpointUrl == null || !enpointUrl.startsWith("https")) {
        _log.info("setupSSL: no HTTPS found -> no setup needed");
        return;//from   ww  w .j  a v  a  2  s  . co  m
    }

    // enable SSL-Debuging
    if (sslDebug) {
        System.setProperty("javax.net.debug", "ssl");
    }

    ConfigurationManagerService cms = ConfigurationManagerService.getInstance();

    // Setting Cert-Props
    System.setProperty("javax.net.ssl.trustStore", cms.getProperty("javax.net.ssl.trustStore"));
    System.setProperty("javax.net.ssl.trustStorePassword", cms.getProperty("javax.net.ssl.trustStorePassword"));
    System.setProperty("javax.net.ssl.keyStore", cms.getProperty("javax.net.ssl.keyStore"));
    System.setProperty("javax.net.ssl.keyStorePassword", cms.getProperty("javax.net.ssl.keyStorePassword"));

    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("URL Host: expected: " + urlHostName + " found: " + session.getPeerHost());
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:com.trsst.Common.java

/**
 * Most trsst nodes run with self-signed certificates, so by default we
 * accept them. While posts are still signed and/or encrypted, a MITM can
 * still refuse our out-going posts and suppress incoming new ones, but this
 * the reason to relay with many trsst servers. Use the -strict option to
 * require CA-signed certificates. Note that nowadays CA-signed certs are no
 * guarantee either.//from w ww .j  av  a 2 s  . co  m
 */
public static void enableAnonymousSSL() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    } };

    SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
        log.error("Can't get SSL context", e);
    } catch (KeyManagementException e) {
        log.error("Can't set SSL socket factory", e);
    }

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    // For apache http client
    Protocol anonhttps = new Protocol("https", (ProtocolSocketFactory) new AnonymSSLSocketFactory(), 443); //
    Protocol.registerProtocol("https", anonhttps);
}

From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java

/**
 * Create a new BeeswaxServiceImpl./*from www.  j  ava  2s  .c om*/
 *
 * @param dtHost The Hue host (ip or hostname).
 * @param dtPort The port Desktop runs on.
 * @param dtHttps Whether Desktop is running https.
 * @param queryLifetime The life time of a cached query.
 */
public BeeswaxServiceImpl(String dtHost, int dtPort, boolean dtHttps, long queryLifetime) {
    LogContext.initLogCapture();
    this.executor = Executors.newCachedThreadPool(new NamingThreadFactory("Beeswax-%d"));
    this.runningQueries = new ConcurrentHashMap<String, RunningQueryState>();
    this.queryLifetime = queryLifetime;

    if (dtPort == -1) {
        this.notifyUrl = null;
    } else {
        String protocol;
        if (dtHttps) {
            try {
                // Disable SSL verification. HUE cert may be signed by untrusted CA.
                SSLContext sslcontext = SSLContext.getInstance("SSL");
                sslcontext.init(null, new DummyX509TrustManager[] { new DummyX509TrustManager() },
                        new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            } catch (NoSuchAlgorithmException ex) {
                LOG.warn("Failed to disable SSL certificate check " + ex);
            } catch (KeyManagementException ex) {
                LOG.warn("Failed to disable SSL certificate check " + ex);
            }
            DummyHostnameVerifier dummy = new DummyHostnameVerifier();
            HttpsURLConnection.setDefaultHostnameVerifier(dummy);
            protocol = "https";
        } else {
            protocol = "http";
        }
        this.notifyUrl = protocol + "://" + dtHost + ":" + dtPort + NOTIFY_URL_BASE;
    }

    // A daemon thread that periodically evict stale RunningQueryState objects
    Thread evicter = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                long now = System.currentTimeMillis();
                for (Map.Entry<String, RunningQueryState> entry : runningQueries.entrySet()) {
                    RunningQueryState rqState = entry.getValue();
                    //safe guard against small value of lifetime, only clean FINISHED or EXCEPTION state
                    if ((rqState.state == QueryState.FINISHED || rqState.state == QueryState.EXCEPTION)
                            && rqState.getAtime() + getQueryLifetime() < now) {
                        String id = entry.getKey();
                        runningQueries.remove(id);
                        LOG.debug("Removed " + rqState.toString());
                        Thread.yield(); // be nice
                    }
                }

                LogContext.garbageCollect(getQueryLifetime());

                long wakeup = now + EVICTION_INTERVAL;
                while (System.currentTimeMillis() < wakeup) {
                    try {
                        Thread.sleep(EVICTION_INTERVAL);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }, "Evicter");
    evicter.setDaemon(true);
    evicter.start();
}

From source file:org.kawanfw.commons.client.http.HttpTransferOne.java

/**
 * If called, self signed SSL certificates will be accepted
 *///w w  w .j a v a 2 s.  c  o  m
private void acceptSelfSignedSslCert() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    // Install the all-trusting trust manager
    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");

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

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

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

}

From source file:ch.lipsch.subsonic4j.internal.SubsonicServiceImpl.java

@Override
public synchronized void disposeService() {
    disposed = true;// w w  w.j a  v a 2s.c  o  m

    // Restores the original hostname verifier.
    if (allowInvalidCerts && defaultHostnameVerifier != null) {
        HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
    }
}

From source file:com.cssn.samplesdk.ShowDataActivity.java

private JSONObject sendJsonRequest(int port, String uri, JSONObject param)
        throws ClientProtocolException, IOException, JSONException {
    //HttpClient httpClient = new DefaultHttpClient();
    DefaultHttpClient client = new DefaultHttpClient();
    X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SchemeRegistry registry = new SchemeRegistry();

    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    HttpPost httpPost = new HttpPost(uri);
    httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    httpPost.addHeader("dataType", "json");

    if (param != null) {
        HttpEntity bodyEntity = new StringEntity(param.toString(), "utf8");
        httpPost.setEntity(bodyEntity);//w w w .  ja v a  2 s.c om
    }

    try {
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        String result = null;
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
                sb.append(line + "\n");

            result = sb.toString();
            instream.close();
        }

        httpPost.abort();
        return result != null ? new JSONObject(result) : null;
    } catch (Exception e1) {
        e1.printStackTrace();
        return null;
    }

}

From source file:com.dynatrace.license.count.monitor.counter.java

public void disableCertificateValidation() {
    log.finer("Entering disableCertificateValidation method");
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }/*  w  w  w  .j ava 2s . c o  m*/

        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) {
    }

    log.finer("Exiting disableCertificateValidation method");
}

From source file:org.codice.alliance.nsili.client.NsiliClient.java

private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from   w ww.ja  v a  2s .c o  m
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
            return;
        }

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

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

    // Set HttpsURLConnection settings
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HostnameVerifier hostnameVerifier = (s, sslSession) -> s.equalsIgnoreCase(sslSession.getPeerHost());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}

From source file:com.maxl.java.aips2sqlite.AllDown.java

private void setNoValidation() throws Exception {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from ww  w .  j  ava  2  s  . c  o m*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // Do nothing
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // Do nothing
        }
    } };

    // Install the all-trusting trust manager      
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

private void trust_Every_ssl_cert() {
    // NEVER enable this on a production release!!!!!!!!!!
    try {/*from  ww  w .  j  ava  2  s.  c  om*/
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                Log.d("aagtl", "DANGER !!! trusted hostname=" + hostname + " DANGER !!!");
                // return true -> mean we trust this cert !! DANGER !! DANGER !!
                return true;
            }
        });
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                Log.d("aagtl", "DANGER !!! 222222222");
                return new java.security.cert.X509Certificate[0];
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
                Log.d("aagtl", "DANGER !!! 333333333");
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws java.security.cert.CertificateException {
                Log.d("aagtl", "DANGER !!! 444444444444");
            }
        } }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // NEVER enable this on a production release!!!!!!!!!!
}