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:net.subclient.subsonic.SubsonicConnection.java

/**
 * Prepares HTTPS connections to accept any domains and self-signed certificates
 * @throws NoSuchAlgorithmException /*from   w  w w .j  a  va  2s .  co  m*/
 * @throws KeyManagementException 
 */
private void setSSLProperties() throws NoSuchAlgorithmException, KeyManagementException {
    //Disable certificate chacks to force trust self-signed certificates
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };
    SSLContext sc = null;
    sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    //Set a hostname verifier that trust any hostname
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

From source file:com.lxh.util.image.OtherUtils.java

/**
 * HttpS/*from   ww w  .  ja va 2s  .  co m*/
 */
public static void trustAllHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (sslSocketFactory == null) {
        //            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        //                @Override
        //                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        //                    return null;
        //                }
        //
        //                @Override
        //                public void checkClientTrusted(X509Certificate[] certs,
        //                                               String authType) {
        //                }
        //
        //                @Override
        //                public void checkServerTrusted(X509Certificate[] certs,
        //                                               String authType) {
        //                }
        //            }
        //            };
        //            try {
        //                SSLContext sslContext = SSLContext.getInstance("TLS");
        //                sslContext.init(null, trustAllCerts, null);
        //                sslSocketFactory = sslContext.getSocketFactory();
        //            } catch (Throwable e) {
        //                LogUtils.e(e.getMessage(), e);
        //            }
    }

    if (sslSocketFactory != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection
                .setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    }
}

From source file:net.sf.taverna.cagrid.activity.CaGridActivity.java

/**
 * This static block is needed in case some of the caGrid services require
 * https which is more than likely and needs to be executed before we start
 * loading caGrid services or otherwise some of these services will fail.
 * Some caGrid services requiring https have a weird CN in their server
 * certificates - instead of CN=<HOSTNAME> they have CN="host/"+<HOSTNAME>,
 * i.e. string "host/" prepended so we have to tell Java's SSL to accept
 * these hostnames as well. This is not very good at is sets this hostname
 * verifier across all https connections created in the JVM from now on, but
 * solves the problem with such caGrid services.
 * /*from ww w. ja  v a 2 s.co  m*/
 */
protected static void setHostNameVerifier() {
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String hostName, SSLSession session) {
            String hostNameFromCertificate = null;
            try {
                hostNameFromCertificate = session.getPeerPrincipal().getName().substring(3,
                        session.getPeerPrincipal().getName().indexOf(','));
            } catch (SSLPeerUnverifiedException e) {
                e.printStackTrace();
                return false;
            }
            logger.info("Hostname verifier: host from url: " + hostName + " vs. host from certificate: "
                    + hostNameFromCertificate);
            //return (hostName.equals(hostNameFromCertificate) || ("host/"+hostName).equals(hostNameFromCertificate));
            //force no-verification, dangerous!!!
            System.out.println(hostName + "\nis using a certificate issued to:\n " + hostNameFromCertificate);
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:com.adguard.compiler.Main.java

/**
 * Disable SSL validation (it may work wrong sometimes)
 *
 * @throws NoSuchAlgorithmException/*from   w ww. ja v  a 2s .  c  o  m*/
 * @throws KeyManagementException
 */
private static void disableSslValidation() throws NoSuchAlgorithmException, KeyManagementException {
    // 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 = 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);
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core.AgentUtilOperations.java

public static void setHTTPSConfigurations() {
    String apimEndpoint = AgentManager.getInstance().getAgentConfigs().getApimGatewayEndpoint();
    System.setProperty("javax.net.ssl.trustStore", AgentConstants.DEVICE_KEYSTORE);
    System.setProperty("javax.net.ssl.trustStorePassword", AgentConstants.DEVICE_KEYSTORE_PASSWORD);

    try {/*from  w  w  w . j a v a  2s.co m*/
        final String apimHost = TransportUtils.getHostAndPort(apimEndpoint).get(AgentConstants.HOST_PROPERTY);

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return hostname.equals(apimHost);
            }
        });
    } catch (TransportHandlerException e) {
        log.error(AgentConstants.LOG_APPENDER
                + "Failed to set HTTPS HostNameVerifier to the APIMServer-Host using the APIM-Endpoint "
                + "string [" + apimEndpoint + "].");
        log.error(AgentConstants.LOG_APPENDER + e);
    }
}

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

private static void disableSSLVerification() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }// w w w  .  j  ava2  s.  c o m

        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:org.wso2.carbon.identity.sts.passive.ui.PassiveSTS.java

private void openURLWithNoTrust(String realm) throws IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from  w w  w  .j a v  a  2 s . c  om
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // Nothing to implement
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // Nothing to implement
        }
    } };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        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());
        SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
        String renegotiation = System.getProperty("sun.security.ssl.allowUnsafeRenegotiation");
        try {
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
            new URL(realm).getContent();
        } finally {
            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
            HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
            System.getProperty("sun.security.ssl.allowUnsafeRenegotiation", renegotiation);
        }
    } catch (Exception ignore) {
        if (log.isDebugEnabled()) {
            log.debug("Error while installing trust manager", ignore);
        }
    }
}

From source file:org.craftercms.studio.impl.v1.service.cmis.CmisServiceImpl.java

private Session createCMISSession(DataSourceRepositoryTO config)
        throws CmisUnavailableException, CmisTimeoutException {

    if (config.isUseSsl()) {
        SSLContext sc = null;/*from  w ww . j  av a  2 s  .c om*/
        try {
            sc = getSSLContext();
            // Ignore differences between given hostname and certificate hostname
            HostnameVerifier hv = (hostname, session) -> true;
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            logger.error("Error initializing SSL context", e);
        }
    }

    // Create a SessionFactory and set up the SessionParameter map
    SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
    Map<String, String> parameter = new HashMap<String, String>();
    parameter.put(SessionParameter.USER, config.getUsername());
    parameter.put(SessionParameter.PASSWORD, config.getPassword());

    // connection settings - we're connecting to a public cmis repo,
    // using the AtomPUB binding, but there are other options here,
    // or you can substitute your own URL
    parameter.put(SessionParameter.ATOMPUB_URL, config.getUrl());
    parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
    parameter.put(SessionParameter.COOKIES, "true");

    // find all the repositories at this URL - there should only be one.
    List<Repository> repositories = new ArrayList<Repository>();
    repositories = sessionFactory.getRepositories(parameter);

    // create session with the first (and only) repository
    Repository repository = repositories.get(0);
    parameter.put(SessionParameter.REPOSITORY_ID, repository.getId());
    Session session = null;
    try {
        session = sessionFactory.createSession(parameter);
    } catch (CmisConnectionException e) {
        throw new CmisTimeoutException(e);
    } catch (CmisBaseException e) {
        throw new CmisUnavailableException(e);
    }

    return session;
}