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.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./* ww  w  .  j a  v a2 s. c o 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:org.kawanfw.commons.client.http.HttpTransferOne.java

/**
 * If called, self signed SSL certificates will be accepted
 */// w  ww .ja  va  2s.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: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];
        }//from w ww.j a v  a2s.  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:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Downloads the string that's in the url with any certificate.
 *//*from w ww.j ava 2s .  com*/
private String downloadWithoutCA(String url_string) {
    String string = "";
    try {

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        class DefaultTrustManager implements 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;
            }
        }

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());

        URL url = new URL(url_string);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(context.getSocketFactory());
        urlConnection.setHostnameVerifier(hostnameVerifier);
        string = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next();
        System.out.println("String ignoring certificate = " + string);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        string = formatErrorMessage(R.string.malformed_url);
    } catch (IOException e) {
        // The downloaded certificate doesn't validate our https connection.
        e.printStackTrace();
        string = formatErrorMessage(R.string.certificate_error);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return string;
}

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/* w w w .j  ava 2  s  . co  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:org.wso2.am.integration.tests.other.APIImportExportTestCase.java

/**
 * Upload a file to the given URL/*from   w ww  . j ava  2 s . c o  m*/
 *
 * @param importUrl URL to be file upload
 * @param fileName  Name of the file to be upload
 * @throws IOException throws if connection issues occurred
 */
private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException {
    //open import API url connection and deploy the exported API
    URL url = new URL(importUrl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    FileBody fileBody = new FileBody(fileName);
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);

    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER,
            "Basic " + encodeCredentials(user, pass));
    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String temp;
    StringBuilder response = new StringBuilder();
    while ((temp = read.readLine()) != null) {
        response.append(temp);
    }
    Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response);
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Write REST request to {@link HttpsURLConnection}.
 * /*from  w ww . j  a v  a 2 s. c  o  m*/
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP method type (GET, POST, PUT etc.)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param requestFileName String File name of the file which contains request body data.
 * @param parametersMap Map<String, String> Additional parameters which is not predefined in the
 *        properties file.
 * @return {@link HttpsURLConnection} object.
 * @throws IOException @
 */
private HttpsURLConnection writeRequestHTTPS(String endPoint, String httpMethod, byte responseType,
        Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap,
        boolean isIgnoreHostVerification) throws IOException {

    String requestData = "";

    if (requestFileName != null && !requestFileName.isEmpty()) {

        requestData = loadRequestFromFile(requestFileName, parametersMap);

    } else if (responseType == RestResponse.JSON_TYPE) {
        requestData = "{}";
    }
    OutputStream output = null;

    URL url = new URL(endPoint);
    HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
    // Disable automatic redirects
    httpsConnection.setInstanceFollowRedirects(false);
    httpsConnection.setRequestMethod(httpMethod);

    if (isIgnoreHostVerification) {
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {

                return true;
            }
        });
    }

    for (String key : headersMap.keySet()) {
        httpsConnection.setRequestProperty(key, headersMap.get(key));
    }

    if (httpMethod.equalsIgnoreCase("POST") || httpMethod.equalsIgnoreCase("PUT")) {
        httpsConnection.setDoOutput(true);
        try {

            output = httpsConnection.getOutputStream();
            output.write(requestData.getBytes(Charset.defaultCharset()));

        } finally {

            if (output != null) {
                try {
                    output.close();
                } catch (IOException logOrIgnore) {
                    log.error("Error while closing the connection");
                }
            }

        }
    }

    return httpsConnection;
}

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  a  v  a2s.c o  m
        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!!!!!!!!!!
}

From source file:io.swagger.client.ApiClient.java

/**
 * Apply SSL related settings to httpClient according to the current values of
 * verifyingSsl and sslCaCert.// w ww  . j a v  a  2 s.c o  m
 */
private void applySslSettings() {
    try {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;
        HostnameVerifier hostnameVerifier = null;
        if (!verifyingSsl) {
            TrustManager trustAll = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

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

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            trustManagers = new TrustManager[] { trustAll };
            hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
        } else if (sslCaCert != null) {
            char[] password = null; // Any password will work.
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
            if (certificates.isEmpty()) {
                throw new IllegalArgumentException("expected non-empty set of trusted certificates");
            }
            KeyStore caKeyStore = newEmptyKeyStore(password);
            int index = 0;
            for (Certificate certificate : certificates) {
                String certificateAlias = "ca" + Integer.toString(index++);
                caKeyStore.setCertificateEntry(certificateAlias, certificate);
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(caKeyStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        }

        if (keyManagers != null || trustManagers != null) {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagers, trustManagers, new SecureRandom());
            httpClient.setSslSocketFactory(sslContext.getSocketFactory());
        } else {
            httpClient.setSslSocketFactory(null);
        }
        httpClient.setHostnameVerifier(hostnameVerifier);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java

private static Client getRestClient(String targetUrl) {

    if (clients.containsKey(targetUrl)) {
        return clients.get(targetUrl);
    }/*  www  .  j  a va2  s.  c  o m*/

    Client client = null;
    if (targetUrl != null) {
        if (targetUrl.startsWith("https://")) {
            try {
                // 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) {
                    }
                } };
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(allHostsValid)
                        .build();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
        } else {
            client = ClientBuilder.newClient();

        }
    }
    if (client == null) {
        return null;
    }

    client.property(ClientProperties.CONNECT_TIMEOUT, 1000);
    client.property(ClientProperties.READ_TIMEOUT, 3000);
    /*
    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(contextServerSettings.getContextServerUsername(), contextServerSettings.getContextServerPassword());
    client.register(feature);
    */
    clients.put(targetUrl, client);
    return client;
}