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:org.apache.fineract.infrastructure.sms.scheduler.SmsMessageScheduledJobServiceImpl.java

/** 
 * prevents the SSL security certificate check 
 **//*  w w  w  .  jav a  2s  .  c  o  m*/
private void trustAllSSLCertificates() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

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

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

    catch (Exception e) {
        // do nothing
    }
}

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

private synchronized void allowUntrustedCerts() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
    SSLContext.setDefault(ctx);//from   ww w  .j a v a2s.  c  om

    HostnameVerifier hv = new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:open.hyperion.nimblestorage.connection.NimbleStorageAPIFactory.java

public ClientConfig configureClient() throws NoSuchAlgorithmException, KeyManagementException {

    TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
        @Override//from   w w w .  j  av  a  2 s .  com
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (java.security.GeneralSecurityException ex) {
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

    ClientConfig config = new DefaultClientConfig();
    try {
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                }, ctx));
    } catch (Exception e) {
    }
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    return config;
}

From source file:net.myrrix.client.ClientRecommender.java

private SSLSocketFactory buildSSLSocketFactory() throws IOException {

    final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override/*from   w  w w. j a v  a  2 s  .  c o m*/
        public boolean verify(String hostname, SSLSession sslSession) {
            return ignoreHTTPSHost || "localhost".equals(hostname) || "127.0.0.1".equals(hostname)
                    || defaultVerifier.verify(hostname, sslSession);
        }
    });

    try {

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File trustStoreFile = config.getKeystoreFile().getAbsoluteFile();
        String password = config.getKeystorePassword();
        Preconditions.checkNotNull(password);

        InputStream in = new FileInputStream(trustStoreFile);
        try {
            keyStore.load(in, password.toCharArray());
        } finally {
            in.close();
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        SSLContext ctx;
        try {
            ctx = SSLContext.getInstance("TLSv1.1"); // Java 7 only
        } catch (NoSuchAlgorithmException ignored) {
            log.info("TLSv1.1 unavailable, falling back to TLSv1");
            ctx = SSLContext.getInstance("TLSv1"); // Java 6       
            // This also seems to be necessary:
            if (System.getProperty("https.protocols") == null) {
                System.setProperty("https.protocols", "TLSv1");
            }
        }
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx.getSocketFactory();

    } catch (NoSuchAlgorithmException nsae) {
        // can't happen?
        throw new IllegalStateException(nsae);
    } catch (KeyStoreException kse) {
        throw new IOException(kse);
    } catch (KeyManagementException kme) {
        throw new IOException(kme);
    } catch (CertificateException ce) {
        throw new IOException(ce);
    }
}

From source file:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {//from   w w w.  j  a  v a2  s  .c o m
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat(
                "/com.microfocus.application.automation.tools.srf.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String credentialsId = document.getElementsByTagName("credentialsId").item(0).getTextContent();
        UsernamePasswordCredentials credentials = CredentialsProvider.findCredentialById(credentialsId,
                StandardUsernamePasswordCredentials.class, build, URIRequirementBuilder.create().build());

        String app = credentials.getUsername();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = credentials.getPassword().getPlainText();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();

        // Normalize SRF server URL string if needed
        if (server.substring(server.length() - 1).equals("/")) {
            server = server.substring(0, server.length() - 1);
        }

        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0) != null
                    ? document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim()
                    : null;
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0) != null
                    ? document.getElementsByTagName("srfTunnelPath").item(0).getTextContent()
                    : null;
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {// www. j  a v  a2  s.com
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat("/com.hpe.application.automation.tools.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String app = document.getElementsByTagName("srfAppName").item(0).getTextContent();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = document.getElementsByTagName("srfSecretName").item(0).getTextContent();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();
        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim();
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0).getTextContent();
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.C3PREmbeddedTomcatTestBase.java

/**
 * Code of this method was simply Googled.
 *///from   w ww.  ja  v  a2s.c om
void disableSSLVerification() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }

    com.sun.net.ssl.HostnameVerifier hv = new com.sun.net.ssl.HostnameVerifier() {

        public boolean verify(String urlHostname, String certHostname) {
            return true;
        }
    };
    com.sun.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);

    HostnameVerifier hv2 = new HostnameVerifier() {

        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv2);

}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static File downloadTM(final String url, final String authUrl, final String username,
        final String password, final int timeout) throws IOException {
    InputStream in = null;/*from  w w  w  .j  a  v a  2 s.  c om*/
    OutputStream out = null;

    try {
        final URL u = new URL(url);
        final URLConnection urlc = u.openConnection();

        if (timeout != 0) {
            urlc.setConnectTimeout(timeout);
            urlc.setReadTimeout(timeout);
        }

        if (urlc instanceof HttpsURLConnection) {
            final String cookie = getTmCookie(authUrl, username, password, timeout).toString();

            final HttpsURLConnection http = (HttpsURLConnection) urlc;
            http.setInstanceFollowRedirects(false);
            http.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String arg0, final SSLSession arg1) {
                    return true;
                }
            });
            http.setRequestMethod(GET_STR);
            http.setAllowUserInteraction(true);
            http.addRequestProperty("Cookie", cookie);
        }

        in = urlc.getInputStream();

        final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
        out = new FileOutputStream(outputFile);

        IOUtils.copy(in, out);
        return outputFile;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:org.apache.openmeetings.web.pages.auth.SignInPage.java

private static void prepareConnection(URLConnection connection) {
    if (!(connection instanceof HttpsURLConnection))
        return;// ww  w  .j  a  va 2  s .  c o m
    ConfigurationDao configurationDao = getBean(ConfigurationDao.class);
    Boolean ignoreBadSSL = configurationDao.getConfValue(CONFIG_IGNORE_BAD_SSL, String.class, "no")
            .equals("yes");
    if (!ignoreBadSSL)
        return;
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

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

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

    } };
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

        });
    } catch (Exception e) {
        log.error("[prepareConnection]", e);
    }
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse putWithBasicAuth(String uri, String requestQuery, String contentType,
        String userName, String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;// w  ww. j a  va  2 s . c o m
        conn.setRequestProperty("Authorization", "Basic " + encode);
        conn.setDoOutput(true); // Triggers POST.
        conn.setRequestProperty("Content-Type", contentType);
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", "" + Integer.toString(requestQuery.getBytes().length));
        conn.setUseCaches(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(requestQuery);
        conn.setReadTimeout(10000);
        conn.connect();
        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            wr.flush();
            wr.close();
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}