Example usage for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier.

Prototype

public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:com.ibm.sbt.services.util.SSLUtil.java

public static DefaultHttpClient wrapHttpClient(DefaultHttpClient base) {
    try {//from   w w  w  . j  a  v  a 2s . c o m
        // Create and assign a dummy TrustManager
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);

        // When Apache Client AllowAllHostnameVerifier is strict, this should be used
        // Stays here for reference
        X509HostnameVerifier verifier = new X509HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }

            @Override
            public void verify(String s, SSLSocket sslSession) throws IOException {
            }

            @Override
            public void verify(String s, String[] ss1, String[] ss2) throws SSLException {
            }

            @Override
            public void verify(String s, X509Certificate cerst) throws SSLException {
            }

        };
        ssf.setHostnameVerifier(verifier);

        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.kenai.redminenb.repository.RedmineRepository.java

static PoolingClientConnectionManager createConnectionManager() throws SSLInitializationException {
    SSLSocketFactory socketFactory = SSLSocketFactory.getSystemSocketFactory();
    socketFactory.setHostnameVerifier(new X509HostnameVerifier() {
        @Override//from   www. ja v a 2s.c  o  m
        public void verify(String string, SSLSocket ssls) throws IOException {
            if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls.getSession())) {
                throw new SSLException("Hostname did not verify");
            }
        }

        @Override
        public void verify(String string, X509Certificate xc) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public boolean verify(String string, SSLSession ssls) {
            return HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls);
        }
    });
    PoolingClientConnectionManager connectionManager = RedmineManagerFactory
            .createConnectionManager(Integer.MAX_VALUE, socketFactory);
    return connectionManager;
}

From source file:org.jssec.android.https.vulnerables.VulnerableSamples.java

public void allowAllHostnameVerifier() {
    SSLSocketFactory sf = null;

    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:com.hp.mercury.ci.jenkins.plugins.OOBuildStep.java

private static void initializeHttpClient(DescriptorImpl descriptor) {

    final int maxConnectionsPerRoute = 100;
    final int maxConnectionsTotal = 100;

    ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager();
    threadSafeClientConnManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
    threadSafeClientConnManager.setMaxTotal(maxConnectionsTotal);

    httpClient = new DefaultHttpClient(threadSafeClientConnManager);
    if (descriptor.isIgnoreSsl()) {
        threadSafeClientConnManager.getSchemeRegistry()
                .register(new Scheme("https", 443, new FakeSocketFactory()));
    } else if (descriptor.getKeystorePath() != null) {
        try {//from w  w w . j  ava  2 s  . com
            SSLSocketFactory sslSocketFactory = sslSocketFactoryFromCertificateFile(
                    descriptor.getKeystorePath(), decrypt(descriptor.getKeystorePassword()).toCharArray());
            sslSocketFactory.setHostnameVerifier(new BrowserCompatHostnameVerifier());
            // For less strict rules in dev mode you can try
            //sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
            threadSafeClientConnManager.getSchemeRegistry()
                    .register(new Scheme("https", 443, sslSocketFactory));
        } catch (NoSuchAlgorithmException e) {
            LOG.error("Could not register https scheme: ", e);
        } catch (KeyManagementException e) {
            LOG.error("Could not register https scheme: ", e);
        } catch (KeyStoreException e) {
            LOG.error("Could not register https scheme: ", e);
        } catch (UnrecoverableKeyException e) {
            LOG.error("Could not register https scheme: ", e);
        } catch (IOException e) {
            LOG.error("Could not load keystore file: ", e);
        } catch (CertificateException e) {
            LOG.error("Could not load keystore file: ", e);
        }
    }

    final HttpParams params = httpClient.getParams();
    final int timeoutInSeconds = descriptor.getTimeout() * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutInSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutInSeconds);
    HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);

    for (OOServer s : descriptor.getOoServers(true).values()) {

        URL url = null;
        try {
            url = new URL(s.getUrl());
        } catch (MalformedURLException mue) {
            //can't happen, we pre-validate the URLS during configuration and set active to false if bad.
        }

        //check why it doesn't use the credentials provider
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, "basic"),
                new UsernamePasswordCredentials(s.getUsername(), decrypt(s.getPassword())));
    }

}

From source file:ee.vvk.ivotingverification.util.CustomHttpsClient.java

private SSLSocketFactory newSslSocketFactory() {
    KeyStore trustStore;//w  w w.j ava 2  s . com
    try {

        trustStore = Util.loadTrustStore((Activity) context);

        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        return sf;
    } catch (Exception e) {
        if (Util.DEBUGGABLE) {
            Log.e(TAG, "Tehniline viga: " + e.getMessage(), e);
        }
        Util.startErrorIntent((Activity) context, C.badServerResponseMessage, true);
    }

    return null;
}

From source file:org.apache.reef.runtime.hdinsight.client.sslhacks.UnsafeClientConstructor.java

@Override
public CloseableHttpClient newInstance() {
    try {//from   w  w w  .ja  v  a  2 s  .co m
        final SSLSocketFactory socketFactory = new SSLSocketFactory(this.getSSLContext());
        socketFactory.setHostnameVerifier(new UnsafeHostNameVerifier());
        final SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("https", 443, socketFactory));
        final ClientConnectionManager clientConnectionManager = new BasicClientConnectionManager(
                schemeRegistry);
        return new DefaultHttpClient(clientConnectionManager);
    } catch (final KeyManagementException | NoSuchAlgorithmException ex) {
        throw new RuntimeException("Unable to instantiate HTTP Client", ex);
    }
}

From source file:com.lonepulse.travisjr.net.ZombieConfig.java

@Override
public HttpClient httpClient() {

    HttpClient client = super.httpClient();

    try {/*from   ww  w.ja va 2  s.  c  om*/

        KeyStore keyStore = KeyStore.getInstance("BKS");
        InputStream is = TravisJr.Application.getContext().getResources().openRawResource(R.raw.travisjr);

        try {

            keyStore.load(is, null);
        } finally {

            is.close();
        }

        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(keyStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        SchemeRegistry schemeRegistry = ((ThreadSafeClientConnManager) client.getConnectionManager())
                .getSchemeRegistry();

        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
    } catch (Exception e) {

        Log.e(getClass().getSimpleName(), "HttpClient configuration with a custom SSLSocketFactory failed.", e);
    }

    return client;
}

From source file:org.qi4j.library.shiro.StrictX509Test.java

@Test
public void test() throws IOException {
    HttpGet get = new HttpGet(SECURED_SERVLET_PATH);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    DefaultHttpClient client = new DefaultHttpClient();
    SSLSocketFactory sslsf = new SSLSocketFactory(X509FixturesData.clientSSLContext());
    sslsf.setHostnameVerifier(new AllowAllHostnameVerifier()); // For unit testing convenience only, do not use in production
    Scheme https = new Scheme("https", sslsf, httpHost.getPort());
    client.getConnectionManager().getSchemeRegistry().register(https);

    String response = client.execute(httpHost, get, responseHandler);
    assertEquals(ServletUsingSecuredService.OK, response);
}

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.thrift.ThriftAuthClient.java

public ThriftAuthClient(String serverIP, String remoteServerPort, String webContextRoot)
        throws AuthenticationException {
    try {// ww w .j  a  v  a  2s.c om
        TrustManager easyTrustManager = new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        //skip host name verification
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(remoteServerPort));

        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getConnectionManager().getSchemeRegistry().register(httpsScheme);

        //If the webContextRoot is null or /
        if (webContextRoot == null || "/".equals(webContextRoot)) {
            //Assign it an empty value since it is part of the thriftServiceURL.
            webContextRoot = "";
        }
        String thriftServiceURL = "https://" + serverIP + ":" + remoteServerPort + webContextRoot + "/"
                + "thriftAuthenticator";
        client = new THttpClient(thriftServiceURL, httpClient);

    } catch (TTransportException e) {
        throw new AuthenticationException("Error in creating thrift authentication client..");
    } catch (Exception e) {
        throw new AuthenticationException("Error in creating thrift authentication client..");
    }
}

From source file:eu.musesproject.client.connectionmanager.TLSManager.java

/**
 * Create SSLFactory object using certificate saved in the device
 * @return SSLSocketFactory/*from   ww w .  j  ava 2 s.c o m*/
 */

private SSLSocketFactory newSslSocketFactory() {
    try {
        InputStream in = new ByteArrayInputStream(MusesUtils.getCertificate().getBytes());
        KeyStore trustedStore = null;

        if (in != null) {
            trustedStore = convertCerToBKS(in, "muses alias", "muses11".toCharArray());
        }
        SSLSocketFactory sf = new SSLSocketFactory(trustedStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}