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.adguard.compiler.Main.java

/**
 * Disable SSL validation (it may work wrong sometimes)
 *
 * @throws NoSuchAlgorithmException/*from w  w w  . jav  a2  s .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.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//w w  w .  j ava 2  s.c o m
        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:com.hotelbeds.distribution.hotel_api_sdk.HotelApiClient.java

public void init() {
    // @formatter:off
    restTemplate = new OkHttpClient.Builder().writeTimeout(connectionRequestTimeout, TimeUnit.MILLISECONDS)
            .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
            .readTimeout(readTimeout, TimeUnit.MILLISECONDS).addInterceptor(new LoggingRequestInterceptor())
            .hostnameVerifier(new HostnameVerifier() {
                @Override//w w w  .j  av  a2 s .  c om
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            }).build();
    // @formatter:on
    initialised = true;
    executorService = Executors.newFixedThreadPool(8);
    mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}

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

public static HttpsResponse deleteWithBasicAuth(String uri, String contentType, String userName,
        String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;//from   www. j  ava 2 s .  c o  m
        conn.setRequestProperty("Authorization", "Basic " + encode);
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.connect();
        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();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.eurekastreams.server.service.actions.strategies.links.ConnectionFacade.java

/**
 * Get the connection.//from  w w  w  .  j a va  2s.c o m
 *
 * @param inUrl
 *            the url.
 * @param inAccountId
 *            account id of the user making the request.
 * @return the connection.
 * @throws MalformedURLException
 *             If the URL is invalid.
 */
protected HttpURLConnection getConnection(final String inUrl, final String inAccountId)
        throws MalformedURLException {
    HttpURLConnection connection = null;

    if (proxyHost.length() > 0) {
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", proxyPort);
    }

    log.info("Using Proxy: " + proxyHost + ":" + proxyPort);

    URL url = getUrl(inUrl);
    try {
        // Some sites e.g. Google Images and Digg will not respond to an unrecognized User-Agent.

        if ("https".equals(url.getProtocol())) {
            log.trace("Using HTTPS");

            // Install the all-trusting trust manager
            try {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                log.trace("Installed all-trusting trust manager.");
            } catch (Exception e) {
                log.error("Error setting SSL Context");
            }

            connection = (HttpsURLConnection) url.openConnection();

            ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String hostname, final SSLSession session) {
                    log.trace("Accepting host name.");
                    return true;
                }
            });
        } else {
            URLConnection plainConnection = url.openConnection();

            if (plainConnection instanceof HttpURLConnection) {
                log.trace("Using HTTP");
                connection = (HttpURLConnection) plainConnection;
            } else {
                log.info("Closing non-HTTP connection.");
                return null;
            }
        }

        connection.setConnectTimeout(connectionTimeOut);

        // Decorate the connection.
        for (ConnectionFacadeDecorator decorator : decorators) {
            decorator.decorate(connection, inAccountId);
        }
    } catch (Exception e) {
        log.error("caught exception: ", e);
    }

    return connection;
}

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  . c o  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 ww.  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:com.sitewhere.wso2.identity.scim.Wso2ScimAssetModule.java

/**
 * Creates a transport that allows missing certificates to be ignored.
 * //from   www . j  a v  a  2 s.com
 * @param username
 * @param password
 * @return
 */
protected ClientHttpRequestFactory createSecureTransport(String username, String password) {
    HostnameVerifier nullHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    HttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(nullHostnameVerifier)
            .setSSLContext(createContext()).build();

    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);

    return requestFactory;
}

From source file:org.sakaiproject.contentreview.turnitin.util.TurnitinAPIUtil.java

public static InputStream callTurnitinReturnInputStream(String apiURL, Map<String, Object> parameters,
        String secretKey, int timeout, Proxy proxy, boolean isMultipart)
        throws TransientSubmissionException, SubmissionException {
    InputStream togo = null;/*from   ww w  . ja va 2 s  . c  o m*/

    StringBuilder apiDebugSB = new StringBuilder();

    if (!parameters.containsKey("fid")) {
        throw new IllegalArgumentException("You must to include a fid in the parameters");
    }

    //if (!parameters.containsKey("gmttime")) {
    parameters.put("gmtime", getGMTime());
    //}

    /**
     * Some debug logging
     */
    if (log.isDebugEnabled()) {
        Set<Entry<String, Object>> ets = parameters.entrySet();
        Iterator<Entry<String, Object>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, Object> entr = it.next();
            log.debug("Paramater entry: " + entr.getKey() + ": " + entr.getValue());
        }
    }

    List<String> sortedkeys = new ArrayList<String>();
    sortedkeys.addAll(parameters.keySet());

    String md5 = buildTurnitinMD5(parameters, secretKey, sortedkeys);

    HttpsURLConnection connection;
    String boundary = "";
    try {
        connection = fetchConnection(apiURL, timeout, proxy);
        connection.setHostnameVerifier(new HostnameVerifier() {

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

        if (isMultipart) {
            Random rand = new Random();
            //make up a boundary that should be unique
            boundary = Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26)
                    + Long.toString(rand.nextLong(), 26);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        }

        log.debug("HTTPS Connection made to Turnitin");

        OutputStream outStream = connection.getOutputStream();

        if (isMultipart) {
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting Multipart TII CALL:\n");
            }
            for (int i = 0; i < sortedkeys.size(); i++) {
                if (parameters.get(sortedkeys.get(i)) instanceof ContentResource) {
                    ContentResource resource = (ContentResource) parameters.get(sortedkeys.get(i));
                    outStream.write(
                            ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"pdata\"; filename=\""
                                    + resource.getId() + "\"\r\n" + "Content-Type: " + resource.getContentType()
                                    + "\r\ncontent-transfer-encoding: binary" + "\r\n\r\n").getBytes());
                    //TODO this loads the doc into memory rather use the stream method
                    byte[] content = resource.getContent();
                    if (content == null) {
                        throw new SubmissionException("zero length submission!");
                    }
                    outStream.write(content);
                    outStream.write("\r\n".getBytes("UTF-8"));
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ContentHostingResource: ");
                        apiDebugSB.append(resource.getId());
                        apiDebugSB.append("\n");
                    }
                } else {
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ");
                        apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                        apiDebugSB.append("\n");
                    }
                    outStream.write(encodeParam(sortedkeys.get(i), parameters.get(sortedkeys.get(i)).toString(),
                            boundary).getBytes());
                }
            }
            outStream.write(encodeParam("md5", md5, boundary).getBytes());
            outStream.write(("--" + boundary + "--").getBytes());

            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiDebugSB.append("\n");
                apiTraceLog.debug(apiDebugSB.toString());
            }
        } else {
            writeBytesToOutputStream(outStream, sortedkeys.get(0), "=",
                    parameters.get(sortedkeys.get(0)).toString());
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting TII CALL:\n");
                apiDebugSB.append(sortedkeys.get(0));
                apiDebugSB.append(" = ");
                apiDebugSB.append(parameters.get(sortedkeys.get(0)).toString());
                apiDebugSB.append("\n");
            }

            for (int i = 1; i < sortedkeys.size(); i++) {
                writeBytesToOutputStream(outStream, "&", sortedkeys.get(i), "=",
                        parameters.get(sortedkeys.get(i)).toString());
                if (apiTraceLog.isDebugEnabled()) {
                    apiDebugSB.append(sortedkeys.get(i));
                    apiDebugSB.append(" = ");
                    apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                    apiDebugSB.append("\n");
                }
            }

            writeBytesToOutputStream(outStream, "&md5=", md5);
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiTraceLog.debug(apiDebugSB.toString());
            }
        }

        outStream.close();

        togo = connection.getInputStream();
    } catch (IOException t) {
        log.error("IOException making turnitin call.", t);
        throw new TransientSubmissionException("IOException making turnitin call.", t);
    } catch (ServerOverloadException t) {
        throw new TransientSubmissionException("Unable to submit the content data from ContentHosting", t);
    }

    return togo;

}

From source file:org.pentaho.di.trans.steps.rest.Rest.java

private void setConfig() throws KettleException {

    if (data.config == null) {
        // Use ApacheHttpClient for supporting proxy authentication.
        data.config = new DefaultApacheHttpClientConfig();

        if (!Const.isEmpty(data.realProxyHost)) {
            // PROXY CONFIGURATION
            data.config.getProperties().put(DefaultApacheHttpClientConfig.PROPERTY_PROXY_URI,
                    "http://" + data.realProxyHost + ":" + data.realProxyPort);
            if (!Const.isEmpty(data.realHttpLogin) && !Const.isEmpty(data.realHttpPassword)) {
                data.config.getState().setProxyCredentials(AuthScope.ANY_REALM, data.realProxyHost,
                        data.realProxyPort, data.realHttpLogin, data.realHttpPassword);
            }/*from   ww  w .  ja va2s. c o  m*/
        } else {
            if (!Const.isEmpty(data.realHttpLogin)) {
                // Basic authentication
                data.basicAuthentication = new HTTPBasicAuthFilter(data.realHttpLogin, data.realHttpPassword);
            }
        }
        if (meta.isPreemptive()) {
            data.config.getProperties().put(ApacheHttpClientConfig.PROPERTY_PREEMPTIVE_AUTHENTICATION, true);
        }

        // SSL TRUST STORE CONFIGURATION
        if (!Const.isEmpty(data.trustStoreFile)) {

            try {
                KeyStore trustStore = KeyStore.getInstance("JKS");
                trustStore.load(new FileInputStream(data.trustStoreFile),
                        data.trustStorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(trustStore);

                SSLContext ctx = SSLContext.getInstance("SSL");
                ctx.init(null, tmf.getTrustManagers(), null);

                HostnameVerifier hv = new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        if (isDebug()) {
                            logDebug("Warning: URL Host: " + hostname + " vs. " + session.getPeerHost());
                        }
                        return true;
                    }
                };

                data.config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                        new HTTPSProperties(hv, ctx));

            } catch (NoSuchAlgorithmException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.NoSuchAlgorithm"), e);
            } catch (KeyStoreException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.KeyStoreException"), e);
            } catch (CertificateException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.CertificateException"), e);
            } catch (FileNotFoundException e) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "Rest.Error.FileNotFound", data.trustStoreFile), e);
            } catch (IOException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.IOException"), e);
            } catch (KeyManagementException e) {
                throw new KettleException(BaseMessages.getString(PKG, "Rest.Error.KeyManagementException"), e);
            }
        }

    }
}