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

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

Introduction

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

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:org.wso2.identity.sample.webapp.APIInvoker.java

private String callRESTep(String ep) throws Exception {

    PlatformUtils.setKeyStoreProperties();
    PlatformUtils.setKeyStoreParams();//from   w w w.  j a v a  2  s .c o m

    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        SSLSocketFactory sf = null;
        SSLContext sslContext = null;
        StringWriter writer;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, null, null);
        } catch (NoSuchAlgorithmException e) {
            //<YourErrorHandling>
        } catch (KeyManagementException e) {
            //<YourErrorHandling>
        }

        try {
            sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            //<YourErrorHandling>
        }
        Scheme scheme = new Scheme("https", 8243, sf);
        httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
        HttpGet get = new HttpGet(ep);

        // add header
        get.setHeader("Content-Type", "text/xml;charset=UTF-8");
        get.setHeader("Authorization", "Bearer " + oauthToken);
        get.setHeader("x-saml-assertion", SamlConsumerManager.getEncodedAssertion());

        CloseableHttpResponse response = httpClient.execute(get);
        try {
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("API RESULT" + result);
            return result;
        } finally {
            response.close();
        }

    } finally {
        httpClient.close();
    }
}

From source file:no.kantega.kwashc.server.test.SSLProtocolTest.java

private HttpResponse checkClient(Site site, int httpsPort, HttpClient httpclient, String[] protocols,
        String[] ciphers) throws NoSuchAlgorithmException, KeyManagementException, IOException {
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { allowAllTrustManager }, null);

    SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000);

    SSLSocket socket = (SSLSocket) sf.createSocket(params);
    if (protocols != null) {
        socket.setEnabledProtocols(protocols);
    }/*ww  w . j  ava2s  . c  o m*/
    if (ciphers != null) {
        socket.setEnabledCipherSuites(ciphers);
    }

    URL url = new URL(site.getAddress());

    InetSocketAddress address = new InetSocketAddress(url.getHost(), httpsPort);
    sf.connectSocket(socket, address, null, params);

    Scheme sch = new Scheme("https", httpsPort, sf);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    HttpGet request = new HttpGet(
            "https://" + url.getHost() + ":" + site.getSecureport() + url.getPath() + "blog");

    return httpclient.execute(request);
}

From source file:com.waitwha.nessus.server.Server.java

/**
 * Constructor/*from  w  w w .  j a va2  s. c om*/
 *
 * @param url   End-point URL of the Nessus Server. (i.e. https://localhost:8834)
 */
public Server(final String url) {
    this.url = url;

    /*
     * Configure XML parsing.
     */
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        this.builder = factory.newDocumentBuilder();
        log.finest(String.format("Successfully configured XML parsing using builder: %s",
                this.builder.getClass().getName()));

    } catch (ParserConfigurationException e) {
        log.warning(String.format("Could not configure XML parsing: %s", e.getMessage()));

    }

    /*
     * Setup SSL for HttpClient configurations. Here we will configure SSL/TLS to 
     * accept all hosts (no verification on certificates). This is because Nessus by
     * default used a self-generate CA and certificate for the servers. So, a simple 
     * self-signed-strategy will not work as we are not dealing with strictly 
     * self-signed certs, but ones generated and signed by a self-generated CA. 
     * 
     * TODO Perhaps the serial number of the CA is always the same so in the future we
     * could use a strategy to only accept certs by this one serial.
     * 
     * See http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientConfiguration.java.
     * 
     * TODO We need to work on the code here to be more up-to-date. SSLSocketFactory is deprecated, but 
     * finding up-to-date docs on how to use SSLContext with a custom TrustStrategy and not using a KeyStore is
     * not currently available.
     */
    //SSLContext sslContext = SSLContexts.createSystemDefault();
    Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
    try {
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLSocketFactory(new MyTrustStrategy(),
                        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
                .build();
        log.finest(String.format("Configured SSL/TLS connections for %s.", url));

    } catch (Exception e) {
        log.warning(
                String.format("Could not configure SSL/TLS: %s %s", e.getClass().getName(), e.getMessage()));

    }

    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    this.connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
    this.connectionManager.setSocketConfig(socketConfig);
    log.finest(String.format("Configured socket connections for %s.", url));

    this.cookieStore = new BasicCookieStore() {

        private static final long serialVersionUID = 1L;

        /**
         * @see org.apache.http.impl.client.BasicCookieStore#addCookie(org.apache.http.cookie.Cookie)
         */
        @Override
        public synchronized void addCookie(Cookie cookie) {
            log.finest(String.format("[%s] Cookie added: %s=%s", url, cookie.getName(), cookie.getValue()));
            super.addCookie(cookie);
        }

    };
    log.finest(String.format("Configured default/basic cookie storage for connections to %s", url));

}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * Initializes the HTTPs connection/*w  w  w.  j av  a 2  s .  c o m*/
 * 
 * @param sslPort
 *            the number of the port the server should be listening for
 *            SSL/TLS connections
 */
public void InitializeSecure(int sslPort) {
    if (sslPort != -1) {
        SSLSocketFactory sslf = null;
        SSLSocket s = null;
        port = sslPort;
        try {
            // notifyOfProggress(false);
            KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
            trusted.load(null, null);

            sslf = new MySSLSocketFactory(trusted);
            Log.w("Android mobile voting", "1");
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Log.w("Android mobile voting", "2");
            BasicHttpParams params = new BasicHttpParams();
            Log.w("Android mobile voting", "3");
            HttpConnectionParams.setConnectionTimeout(params, 500);
            Log.w("Android mobile voting", "4");
            s = (SSLSocket) sslf.connectSocket(sslf.createSocket(), server.getAddress(), sslPort, null, 0,
                    params);
            if (exc) {
                SSLSession ssls = null;
                ssls = s.getSession();
                final javax.security.cert.X509Certificate[] x = ssls.getPeerCertificateChain();

                for (int i = 0; i < x.length; i++) {

                    parent.mHandler.post(new Runnable() {

                        @Override
                        public void run() {

                            try {
                                parent.askForTrust(getThumbPrint(x[0]), instance);
                            } catch (NoSuchAlgorithmException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (CertificateEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (final Exception ex) {
                                parent.mHandler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        parent.showToast(ex.toString());

                                    }

                                });
                                Log.w("Android Mobile Voting", "400 Error");
                                parent.finish();
                            }

                        }
                    });

                }

            }

            s.startHandshake();

            Scheme https = new Scheme("https", sslf, sslPort);

            schemeRegistry.register(https);
            usingScheme = "https";
            port = sslPort;
            if (!exc)
                retrieveQuestions();
        } catch (final Exception ex) {
            parent.mHandler.post(new Runnable() {

                @Override
                public void run() {
                    parent.showToast(ex.toString());

                }

            });
            // Log.w("Android Mobile Voting", "400 Error");
            parent.finish();

        }
    } else {
        parent.mHandler.post(new Runnable() {

            @Override
            public void run() {
                parent.showNoSSLDialog(instance);

            }

        });
    }

}

From source file:iristk.speech.nuancecloud.NuanceCloudSynthesizer.java

private HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    // Standard HTTP parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);

    // Initialize the HTTP client
    httpclient = new DefaultHttpClient(params);

    // Initialize/setup SSL
    TrustManager easyTrustManager = new X509TrustManager() {
        @Override//from w  w w  .j av a  2s .c o m
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    };

    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 sch = new Scheme("https", sf, PORT); // PORT = 443
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    // Return the initialized instance of our httpclient
    return httpclient;
}

From source file:gov.nih.nci.nbia.StandaloneDMV2.java

private static List<String> connectAndReadFromURL(URL url, String fileName, String userId, String passWd) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override//ww  w.  j  a v  a  2  s  . c  om
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair("serverManifestLoc", fileName));
        if (userId != null && passWd != null) {
            postParams.add(new BasicNameValuePair("userId", userId));
            httpPostMethod.addHeader("password", passWd);
        }

        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("!!!!!Response code for requesting datda file:
        // " + responseCode);

        if (responseCode != HttpURLConnection.HTTP_OK) {
            return null;
        } else {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClientAndroid.java

private SchemeRegistry createRegistry(CouchDbProperties properties)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    SchemeRegistry registry = new SchemeRegistry();
    if ("https".equals(properties.getProtocol())) {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);/* w w w  . ja  v  a2  s.  co m*/
        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme(properties.getProtocol(), sf, properties.getPort()));
    } else {
        registry.register(new Scheme(properties.getProtocol(), PlainSocketFactory.getSocketFactory(),
                properties.getPort()));
    }
    return registry;
}

From source file:com.betaplay.sdk.http.HttpClient.java

/**
 * solving problems with ssl//w w  w . j a  va2s .  com
 * 
 * @param client
 * @return
 */
private DefaultHttpClient sslClient(org.apache.http.client.HttpClient client) {
    try {
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new CustomSSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = client.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, client.getParams());
    } catch (Exception ex) {
        return null;
    }
}

From source file:us.mn.state.health.lims.common.externalLinks.ExternalPatientSearch.java

protected void doSearch() {

    HttpClient httpclient = new DefaultHttpClient();
    setTimeout(httpclient);//  ww  w.  j  a  va2s .  c  om

    HttpGet httpget = new HttpGet(connectionString);
    URI getUri = buildConnectionString(httpget.getURI());
    httpget.setURI(getUri);

    try {
        // Ignore hostname mismatches and allow trust of self-signed certs
        SSLSocketFactory sslsf = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sslsf);
        ClientConnectionManager ccm = httpclient.getConnectionManager();
        ccm.getSchemeRegistry().register(https);

        HttpResponse getResponse = httpclient.execute(httpget);
        returnStatus = getResponse.getStatusLine().getStatusCode();
        setPossibleErrors();
        setResults(IOUtils.toString(getResponse.getEntity().getContent(), "UTF-8"));
    } catch (SocketTimeoutException e) {
        errors.add("Response from patient information server took too long.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
        // System.out.println("Tinny time out" + e);
    } catch (ConnectException e) {
        errors.add("Unable to connect to patient information form service. Service may not be running");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
        // System.out.println("you no talks? " + e);
    } catch (IOException e) {
        errors.add("IO error trying to read input stream.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
        // System.out.println("all else failed " + e);
    } catch (KeyManagementException e) {
        errors.add("Key management error trying to connect to external search service.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
    } catch (UnrecoverableKeyException e) {
        errors.add("Unrecoverable key error trying to connect to external search service.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
    } catch (NoSuchAlgorithmException e) {
        errors.add("No such encyrption algorithm error trying to connect to external search service.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
    } catch (KeyStoreException e) {
        errors.add("Keystore error trying to connect to external search service.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
    } catch (RuntimeException e) {
        errors.add("Runtime error trying to retrieve patient information.");
        LogEvent.logError("ExternalPatientSearch", "doSearch()", e.toString());
        httpget.abort();
        throw e;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}