Example usage for javax.net.ssl HostnameVerifier HostnameVerifier

List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier

Introduction

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

Prototype

HostnameVerifier

Source Link

Usage

From source file:com.vuze.android.remote.AndroidUtils.java

private static boolean isURLAlive(String URLName, int conTimeout, int readTimeout) {
    try {/*  ww w  .  j  av  a  2  s . co  m*/
        HttpURLConnection.setFollowRedirects(false);

        URL url = new URL(URLName);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection conHttps = (HttpsURLConnection) con;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() },
                        new SecureRandom());
                conHttps.setSSLSocketFactory(ctx.getSocketFactory());
            }

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

        con.setConnectTimeout(conTimeout);
        con.setReadTimeout(readTimeout);
        con.setRequestMethod("HEAD");
        con.getResponseCode();
        if (DEBUG) {
            Log.d(TAG, "isLive? conn result=" + con.getResponseCode() + ";" + con.getResponseMessage());
        }
        return true;
    } catch (Exception e) {
        if (DEBUG) {
            Log.e(TAG, "isLive " + URLName, e);
        }
        return false;
    }
}

From source file:ActualizadorLocal.Clientes.ClienteDispositivos.java

private HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {
        @Override/* w  w  w  .  j  av  a 2s.co m*/
        public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
            return true;
        }
    };
}

From source file:jetbrains.buildServer.vmgr.agent.Utils.java

private static void configureAllowAll(HttpsURLConnection connection) {
    connection.setHostnameVerifier(new HostnameVerifier() {
        @Override/*w w w . j a v  a 2  s .  c om*/
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });

    try {
        connection.setSSLSocketFactory(getSocketFactory());
    } catch (Exception e) {
        throw new RuntimeException("XTrust Failed to set SSL Socket factory", e);
    }

}

From source file:org.sharegov.cirm.StartUp.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];
        }/*  w w w .  j  a  v  a 2  s . c o m*/

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

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("Check server trusted");

        }
    } };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            // TODO Auto-generated method stub
            return true;
        }
    };

    // Install the all-trusting trust manager
    try {
        // SSLContext sc = SSLContext.getInstance("SSL");
        // sc.init(null, trustAllCerts, new SecureRandom());
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        // see:http://stackoverflow.com/questions/1828775/how-to-handle-invalid-ssl-certificates-with-apache-httpclient
        // see:https://code.google.com/p/jsslutils/wiki/ApacheHttpClientUsage
        org.apache.commons.httpclient.protocol.Protocol.registerProtocol("https",
                new org.apache.commons.httpclient.protocol.Protocol("https",
                        (ProtocolSocketFactory) new SslContextedSecureProtocolSocketFactory(ctx, false), 443));
        SSLContext.setDefault(ctx);
    } catch (Exception e) {
    }
}

From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java

public static void trustEverybody(HttpsURLConnection connection) {
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }/*from w ww  .  j  a va 2 s.c  o  m*/
    };

    // Install the all-trusting trust manager and host name verifier
    SSLContext sc = getTrustEverybodySSLContext();

    if (connection == null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } else {
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(allHostsValid);
    }
}

From source file:org.wso2.carbon.mediation.registry.ESBRegistry.java

/**
 * Configure the ESB registry using registry parameters.
 * <p/>/*from  ww w.  jav  a 2  s . c o  m*/
 * root: FILE:directory -   registry is on local host
 * directory is used to access metadata
 * <p/>
 * root: http/https:location -  has to specify one of the following settings
 * localRegistry - location of the local registry
 * metadataService - url of the service to access metadata
 * If none of above parameters are given "registry" FOLDER is taken as the local registry.
 *
 * @param name name of the config
 * @param value value of the config
 */
private void addConfigProperty(String name, String value) {

    if (localRegistry == null) {
        // registry root should always end with "/"
        if (ESBRegistryConstants.LOCAL_REGISTRY_ROOT.endsWith(URL_SEPARATOR)) {
            localRegistry = ESBRegistryConstants.LOCAL_REGISTRY_ROOT;
        } else {
            localRegistry = ESBRegistryConstants.LOCAL_REGISTRY_ROOT + URL_SEPARATOR;
        }
    }
    if (name != null && value != null) {
        if (name.equals("root")) {

            // root should always end with '/'
            // therefore, property keys do not have to begin with '/', which could be misleading
            try {
                URL url = new URL(value);
                if ("file".equals(url.getProtocol())) {
                    try {
                        url.openStream();
                    } catch (IOException ignored) {
                        if (!localRegistry.endsWith(URL_SEPARATOR)) {
                            localRegistry = localRegistry + URL_SEPARATOR;
                        }
                        url = new URL(url.getProtocol() + ":" + localRegistry + url.getPath());
                        try {
                            url.openStream();
                        } catch (IOException e) {
                            log.error("Unable to open a connection to url : " + url, e);
                        }
                    }
                }
                if (url.getProtocol().equals("file")) {
                    registryProtocol = FILE;

                    registryType = ESBRegistryConstants.LOCAL_HOST_REGISTRY;

                    if (url.getPath().endsWith(URL_SEPARATOR)) {
                        localRegistry = RegistryHelper.getSystemDependentPath(url.getPath());
                    } else {
                        localRegistry = RegistryHelper.getSystemDependentPath(url.getPath()) + File.separator;
                    }

                } else if (url.getProtocol().equals("http")) {
                    registryProtocol = HTTP;
                } else if (url.getProtocol().equals("https")) {
                    registryProtocol = HTTPS;
                }

                if (!value.endsWith(URL_SEPARATOR)) {
                    value = value + URL_SEPARATOR;
                }

            } catch (MalformedURLException e) {
                // don't set the root if this is not a valid URL
                handleException("Registry root should be a valid URL.", e);
            }
        }

        if (name.equals("localRegistry")) {
            registryType = ESBRegistryConstants.LOCAL_HOST_REGISTRY;

            // registry root always ends with "/"
            if (!value.endsWith(File.separator)) {
                value = value + File.separator;
            }
            localRegistry = value;
        }

        if (name.equals("matadataService")) {
            registryType = ESBRegistryConstants.REMOTE_HOST_REGISTRY;
            metaDataService = value;
        }

        // check if host name verification is disabled
        if (name.equalsIgnoreCase("disableHostNameVerification")) {
            if (value.equalsIgnoreCase("true")) {
                HostnameVerifier hv = new HostnameVerifier() {
                    public boolean verify(String urlHostName, SSLSession session) {
                        return true;
                    }
                };

                HttpsURLConnection.setDefaultHostnameVerifier(hv);
            }
        }

    } else {
        log.debug("Name and Value must need");
    }
}

From source file:de.bps.webservices.clients.onyxreporter.OnyxReporterConnector.java

private boolean isServiceAvailable(String target) {

    HostnameVerifier hv = new HostnameVerifier() {
        @Override//w ww  . j  a va 2  s  .  co m
        public boolean verify(String urlHostName, SSLSession session) {
            if (urlHostName.equals(session.getPeerHost())) {
                return true;
            } else {
                return false;
            }
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    try {
        URL url = new URL(target + "?wsdl");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sslconn = (HttpsURLConnection) con;
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(SSLConfigurationModule.getKeyManagers(), SSLConfigurationModule.getTrustManagers(),
                    new java.security.SecureRandom());
            sslconn.setSSLSocketFactory(context.getSocketFactory());
            sslconn.connect();
            if (sslconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                sslconn.disconnect();
                return true;
            }
        } else {
            con.connect();
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                con.disconnect();
                return true;
            }
        }
    } catch (Exception e) {
        Tracing.createLoggerFor(getClass()).error("Error while trying to connect to webservice: " + target, e);
    }
    return false;
}

From source file:org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig.java

private void doHostNameVerification() {
    if (!this.getEnableHostNameVerification()) {
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }/*ww w.j  ava2s.  c  o m*/
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
}

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;/*  w w w. ja v a2 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.groupon.odo.bmp.BrowserMobProxyHandler.java

/**
 * Returns a OkHttpClient that ignores SSL cert errors
 * @return/*w  w w .j a  va  2s  .  c om*/
 */
private static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // 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 null;
            }
        } };

        // 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();

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

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