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.gmobi.poponews.util.HttpHelper.java

static void disableSslCheck() {
    if (initialized)
        return;// w w w . j a va 2  s .co  m
    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) {
        }
    } };

    SSLContext sc;
    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);
        initialized = true;
    } catch (Exception e) {
        Logger.error(e);
    }

}

From source file:mendhak.teamcity.stash.api.StashClient.java

private HttpURLConnection GetConnection(String targetURL)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URL url = new URL(targetURL);
    if (targetURL.startsWith("http://")) {
        return (HttpURLConnection) url.openConnection();
    }//  ww  w  .  j a va  2 s .  com

    //Create an all trusting SSL URL Connection
    //For in-house Stash servers with self-signed certs

    // Create a trust manager that does not validate certificate chains
    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) {
        }
    } };

    // 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() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

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

    return (HttpsURLConnection) url.openConnection();

}

From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java

private boolean disableSSL() {
    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }//  w  ww .  java  2s.  co m
    };

    // 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(java.security.cert.X509Certificate[] certs, String authType) {
        }

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

    // install all-trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        return true;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        return false;
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        return false;
    }
}

From source file:hudson.remoting.Launcher.java

/**
 * Bypass HTTPS security check by using free-for-all trust manager.
 *
 * @param _//w  w w.  j  a v a2  s .  com
 *      This is ignored.
 */
@Option(name = "-noCertificateCheck")
public void setNoCertificateCheck(boolean _) throws NoSuchAlgorithmException, KeyManagementException {
    System.out.println("Skipping HTTPS certificate checks altoghether. Note that this is not secure at all.");
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    // bypass host name check, too.
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
}

From source file:net.Downloader.java

public void run() {
    OutputStream os = null;/*ww w  .j  a  v a  2 s .com*/
    InputStream is = null;

    ProgressListener progressListener = new ProgressListener();
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new SSLManager() };

        // Install the all-trusting trust manager
        final 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() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

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

        os = new FileOutputStream(fl);
        is = conn.getInputStream();

        CountingStream dcount = new CountingStream(os);
        dcount.setListener(progressListener);

        status = "Downloading";
        // begin transfer by writing to dcount, not os.
        IOUtils.copy(is, dcount);

    } catch (UnknownHostException u) {
        System.err.println("Uknown Host2");
        u.printStackTrace();
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        try {
            status = "Finished";
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.dirigible.ide.common.io.ProxyUtils.java

private static void setTrustAllSSL() throws IOException {
    try {/*from  ww w.  ja  va  2s.  c  o  m*/
        HttpsURLConnection.setDefaultSSLSocketFactory(createTrustAllSSLContext().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);
    } catch (KeyManagementException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.falcon.client.FalconClient.java

public static AuthenticatedURL.Token getToken(String baseUrl) throws FalconCLIException {
    AuthenticatedURL.Token currentToken = new AuthenticatedURL.Token();
    try {/* w w  w. j ava  2s  .c  o m*/
        URL url = new URL(baseUrl + AUTH_URL);
        // using KerberosAuthenticator which falls back to PsuedoAuthenticator
        // instead of passing authentication type from the command line - bad factory
        HttpsURLConnection.setDefaultSSLSocketFactory(getSslContext().getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
        new AuthenticatedURL(AUTHENTICATOR).openConnection(url, currentToken);
    } catch (Exception ex) {
        throw new FalconCLIException("Could not authenticate, " + ex.getMessage(), ex);
    }

    return currentToken;
}

From source file:org.apache.stratos.adc.mgt.cli.CommandLineService.java

public boolean login(String serverURL, String username, String password, boolean validateLogin)
        throws CommandException {
    try {//from   www. jav a  2  s. c om
        // Following code will avoid validating certificate
        SSLContext sc;
        // Get SSL context
        sc = SSLContext.getInstance("SSL");
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        // 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(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
        throw new RuntimeException("Error while authentication process!", e);
    }

    // Initialize Service Stub
    try {
        initializeApplicationManagementStub(serverURL, username, password);
    } catch (AxisFault e) {
        System.out.println("Error connecting to the back-end");
        throw new CommandException(e);
    }

    try {
        if (validateLogin) {
            String tenantDomain = stub.getTenantDomain();
            if (logger.isDebugEnabled()) {
                logger.debug("Tenant Domain {}", tenantDomain);
            }
            return (tenantDomain != null);
        } else {
            // Just return true as we don't need to validate
            return true;
        }
    } catch (RemoteException e) {
        System.out.println("Authentication failed!");
        throw new CommandException(e);
    }
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.TenantMgtAdminServiceClient.java

/**
 * Create basic SSL connection factory/*ww  w .  j  a  va  2 s.co  m*/
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

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

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:org.hyperic.plugin.vrealize.automation.VRAUtils.java

public static String getWGet(String path) {
    String retValue = null;//www. j a v a 2s  .c o  m
    try {
        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 = 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);
        URL url = new URL(path);
        URLConnection con;
        try {
            con = url.openConnection();
        } catch (Exception e) {
            log.debug("Couldnt connect to vRa API");
            return "";
        }

        Reader reader = new InputStreamReader(con.getInputStream());
        while (true) {
            int ch = reader.read();
            if (ch == -1) {
                break;
            }
            retValue += (char) ch;
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return retValue;
}