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.qi4j.library.http.AbstractSecureJettyTest.java

@BeforeClass
public static void beforeSecureClass() throws IOException, GeneralSecurityException {
    defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        public boolean verify(String string, SSLSession ssls) {
            return true;
        }/*from  ww  w. j  a  v a  2  s .  c  om*/

    });
    KeyStore truststore = KeyStore.getInstance("JCEKS");
    truststore.load(new FileInputStream(TRUSTSTORE_FILE), KS_PASSWORD.toCharArray());
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance(getX509Algorithm());
    caTrustManagerFactory.init(truststore);
    sslCtx.init(null, caTrustManagerFactory.getTrustManagers(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
}

From source file:comsat.sample.tomcat.SampleTomcatTwoConnectorsApplicationTests.java

@Test
public void testHello() throws Exception {
    RestTemplate template = new RestTemplate();
    final MySimpleClientHttpRequestFactory factory = new MySimpleClientHttpRequestFactory(
            new HostnameVerifier() {

                @Override/*from  ww w .  j  a  va 2 s  .c o m*/
                public boolean verify(final String hostname, final SSLSession session) {
                    return true; // these guys are alright by me...
                }
            });
    template.setRequestFactory(factory);

    ResponseEntity<String> entity = template.getForEntity("http://localhost:" + this.port + "/hello",
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertEquals("hello", entity.getBody());

    ResponseEntity<String> httpsEntity = template
            .getForEntity("https://localhost:" + this.context.getBean("port") + "/hello", String.class);
    assertEquals(HttpStatus.OK, httpsEntity.getStatusCode());
    assertEquals("hello", httpsEntity.getBody());
}

From source file:com.frostwire.http.HttpClient.java

private static HostnameVerifier buildHostnameVerifier() {
    return new HostnameVerifier() {
        @Override//  w w w  .  j  a  v  a 2 s.c  om
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
}

From source file:org.keycloak.truststore.JSSETruststoreConfigurator.java

public HostnameVerifier getHostnameVerifier() {
    if (provider == null) {
        return null;
    }//  w w  w.j a  v  a 2s .com

    HostnameVerificationPolicy policy = provider.getPolicy();
    switch (policy) {
    case ANY:
        return new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
    case WILDCARD:
        return new BrowserCompatHostnameVerifier();
    case STRICT:
        return new StrictHostnameVerifier();
    default:
        throw new IllegalStateException("Unknown policy: " + policy.name());
    }
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

/**
 * no-arg constructor for client/*from   w  w w  .ja v  a2s  .  c  om*/
 */
public TankHttpClient4() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
            .setCircularRedirectsAllowed(true).setAuthenticationEnabled(true).setRedirectsEnabled(true)
            .setMaxRedirects(100).build();

    // Make sure the same context is used to execute logically related
    // requests
    context = HttpClientContext.create();
    context.setCredentialsProvider(new BasicCredentialsProvider());
    context.setCookieStore(new BasicCookieStore());
    context.setRequestConfig(requestConfig);
}

From source file:edu.indiana.d2i.sloan.ui.LoginSuccessAction.java

private boolean disableSSL() {
    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }/*from  w  w  w  . ja v  a  2s. c  o 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);
        addActionError(e.getMessage());
        return false;
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        addActionError(e.getMessage());
        return false;
    }
}

From source file:io.getlime.push.configuration.PowerAuthWebServiceConfiguration.java

/**
 * Prepare a correctly configured PowerAuthServiceClient instance with the service
 * URL specified using 'powerauth.service.url' server property.
 *
 * @param marshaller JAXB marshaller/*from w w  w . jav  a 2 s  .c  o  m*/
 * @return Correctly configured PowerAuthServiceClient instance with the service
 * URL specified using 'powerauth.service.url' server property
 */
@Bean
public PowerAuthServiceClient powerAuthClient(Jaxb2Marshaller marshaller) {
    PowerAuthServiceClient client = new PowerAuthServiceClient();
    client.setDefaultUri(powerAuthServiceUrl);
    client.setMarshaller(marshaller);
    client.setUnmarshaller(marshaller);

    // if invalid SSL certificates should be accepted
    if (acceptInvalidSslCertificate) {

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        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) {
            // ... ignore
        }

    }

    // if there is a configuration with security credentials, add interceptor
    if (!clientToken.isEmpty()) {
        ClientInterceptor[] interceptors = new ClientInterceptor[] { securityInterceptor() };
        client.setInterceptors(interceptors);
    }
    return client;
}

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

protected HttpURLConnection getConnection(final String url, final String data, final String requestMethod,
        final long lastFetchTime) throws IOException {
    String method = GET_STR;//from   w  w w. j a v a 2 s .  co m

    if (requestMethod != null) {
        method = requestMethod;
    }

    LOGGER.info(method + "ing: " + url + "; timeout is " + timeout);

    final URLConnection connection = new URL(url).openConnection();

    connection.setIfModifiedSince(lastFetchTime);

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

    final HttpURLConnection http = (HttpURLConnection) connection;

    if (connection instanceof HttpsURLConnection) {
        final HttpsURLConnection https = (HttpsURLConnection) connection;
        https.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
    }

    http.setInstanceFollowRedirects(false);
    http.setRequestMethod(method);
    http.setAllowUserInteraction(true);

    for (final String key : requestProps.keySet()) {
        http.addRequestProperty(key, requestProps.get(key));
    }

    if (method.equals(POST_STR) && data != null) {
        http.setDoOutput(true); // Triggers POST.

        try (final OutputStream output = http.getOutputStream()) {
            output.write(data.getBytes(UTF8_STR));
        }
    }

    connection.connect();

    return http;
}

From source file:com.quarterfull.newsAndroid.reader.HttpJsonRequest.java

private HttpJsonRequest(Context context) {
    client = new OkHttpClient();

    // set location of the keystore
    MemorizingTrustManager.setKeyStoreFile("private", "sslkeys.bks");

    // register MemorizingTrustManager for HTTPS
    try {//w  ww. j  a  va2s  .  c  om
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, MemorizingTrustManager.getInstanceList(context), new java.security.SecureRandom());
        // enables TLSv1.1/1.2 for Jelly Bean Devices
        TLSSocketFactory tlsSocketFactory = new TLSSocketFactory(sc);
        client.setSslSocketFactory(tlsSocketFactory);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    client.setConnectTimeout(10000, TimeUnit.MILLISECONDS);
    client.setReadTimeout(120, TimeUnit.SECONDS);

    // disable hostname verification, when preference is set
    // (this still shows a certification dialog, which requires user interaction!)
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    if (sp.getBoolean(SettingsActivity.CB_DISABLE_HOSTNAME_VERIFICATION_STRING, false))
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    imageClient = client.clone();
    client.interceptors().add(new AuthorizationInterceptor());

    setCredentials(sp.getString(SettingsActivity.EDT_USERNAME_STRING, null),
            sp.getString(SettingsActivity.EDT_PASSWORD_STRING, null),
            sp.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, null));
}

From source file:org.openecomp.sdnc.dmaapclient.SdncOdlConnection.java

public String send(String method, String contentType, String msg) throws IOException {

    LOG.info("Sending REST " + method + " to " + url);
    LOG.info("Message body:\n" + msg);
    String authStr = user + ":" + password;
    String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes()));

    httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr);

    httpConn.setRequestMethod(method);/* w w w  . j  ava2  s. c o  m*/
    httpConn.setRequestProperty("Content-Type", contentType);
    httpConn.setRequestProperty("Accept", contentType);

    httpConn.setDoInput(true);
    httpConn.setDoOutput(true);
    httpConn.setUseCaches(false);

    if (httpConn instanceof HttpsURLConnection) {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier);
    }

    // Write message
    httpConn.setRequestProperty("Content-Length", "" + msg.length());
    DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream());
    outStr.write(msg.getBytes());
    outStr.close();

    // Read response
    BufferedReader respRdr;

    LOG.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage());

    if (httpConn.getResponseCode() < 300) {

        respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
    } else {
        respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
    }

    StringBuffer respBuff = new StringBuffer();

    String respLn;

    while ((respLn = respRdr.readLine()) != null) {
        respBuff.append(respLn + "\n");
    }
    respRdr.close();

    String respString = respBuff.toString();

    LOG.info("Response body :\n" + respString);

    return (respString);

}