Example usage for javax.net.ssl X509TrustManager X509TrustManager

List of usage examples for javax.net.ssl X509TrustManager X509TrustManager

Introduction

In this page you can find the example usage for javax.net.ssl X509TrustManager X509TrustManager.

Prototype

X509TrustManager

Source Link

Usage

From source file:org.lightcouch.CouchDbClientBase.java

/**
 * @return {@link DefaultHttpClient} instance.
 *//*from   w  w w  .j a v a 2  s. com*/
private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
        SchemeSocketFactory ssf = null;
        if (props.getProtocol().equals("https")) {
            TrustManager trustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

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

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SSLSocket socket = (SSLSocket) ssf.createSocket(null);
            socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
        } else {
            ssf = PlainSocketFactory.getSocketFactory();
        }
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
        httpclient = new DefaultHttpClient(ccm);
        host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
        context = new BasicHttpContext();
        // Http params
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                props.getConnectionTimeout());
        int maxConnections = props.getMaxConnections();
        if (maxConnections != 0) {
            ccm.setMaxTotal(maxConnections);
            ccm.setDefaultMaxPerRoute(maxConnections);
        }
        if (props.getProxyHost() != null) {
            HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // basic authentication
        if (props.getUsername() != null && props.getPassword() != null) {
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()),
                    new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
            props.clearPassword();
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(host, basicAuth);
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }
        // request interceptor
        httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws IOException {
                if (log.isInfoEnabled())
                    log.info(">> " + request.getRequestLine());
            }
        });
        // response interceptor
        httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context) throws IOException {
                validate(response);
                if (log.isInfoEnabled())
                    log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
        });
    } catch (Exception e) {
        log.error("Error Creating HTTP client. " + e.getMessage());
        throw new IllegalStateException(e);
    }
    return httpclient;
}

From source file:com.ibm.iotf.client.api.APIClient.java

public APIClient(Properties opt) throws NoSuchAlgorithmException, KeyManagementException {
    boolean isGateway = false;
    String authKeyPassed = null;//from  ww  w. j ava2s . c o  m

    if ("gateway".equalsIgnoreCase(APIClient.getAuthMethod(opt))) {
        isGateway = true;
    } else if ("device".equalsIgnoreCase(APIClient.getAuthMethod(opt))) {
        authKey = "use-token-auth";
    } else {
        authKeyPassed = opt.getProperty("auth-key");
        if (authKeyPassed == null) {
            authKeyPassed = opt.getProperty("API-Key");
        }

        authKey = trimedValue(authKeyPassed);
    }

    String token = opt.getProperty("auth-token");
    if (token == null) {
        token = opt.getProperty("Authentication-Token");
    }
    authToken = trimedValue(token);

    String org = null;
    org = opt.getProperty("org");

    if (org == null) {
        org = opt.getProperty("Organization-ID");
    }

    this.orgId = trimedValue(org);
    this.domain = getDomain(opt);

    if (this.orgId == null || this.orgId.equalsIgnoreCase("quickstart"))
        isQuickstart = true;
    this.mdeviceType = this.getDeviceType(opt);
    this.mdeviceId = this.getDeviceId(opt);
    this.isSecured = this.IsSecuredConnection(opt);
    if (isGateway) {
        authKey = "g/" + this.orgId + '/' + mdeviceType + '/' + mdeviceId;
    }

    TrustManager[] trustAllCerts = null;
    boolean trustAll = false;

    String value = opt.getProperty("Trust-All-Certificates");
    if (value != null) {
        trustAll = Boolean.parseBoolean(trimedValue(value));
    }

    if (trustAll) {
        trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
    }

    sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, trustAllCerts, null);
}

From source file:gov.medicaid.screening.dao.impl.BaseDAO.java

/**
 * Trusts the source by default./*  w ww. ja  v  a 2 s .  c o m*/
 * 
 * @return lax SSL connection manager
 * @throws ServiceException
 *             when an error occurred while setting up SSL connection details
 */
protected ClientConnectionManager getLaxSSLConnectionManager() throws ServiceException {
    try {
        X509TrustManager tm = new X509TrustManager() {
            /**
             * Returns null.
             */
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            /**
             * Does nothing.
             * 
             * @param chain
             *            not used
             * @param authType
             *            not used
             */
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            /**
             * Does nothing.
             * 
             * @param chain
             *            not used
             * @param authType
             *            not used
             */
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        };

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
        Scheme https = new Scheme("https", 443, sf);
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SchemeRegistry sr = new SchemeRegistry();
        sr.register(https);
        sr.register(http);
        return new BasicClientConnectionManager(sr);
    } catch (NoSuchAlgorithmException e) {
        LogUtil.traceError(getLog(), "BaseDAO#getLaxSSLConnectionManager", e);
        throw new ServiceException(ErrorCode.MITA50001.getDesc(), e);
    } catch (KeyManagementException e) {
        LogUtil.traceError(getLog(), "BaseDAO#getLaxSSLConnectionManager", e);
        throw new ServiceException(ErrorCode.MITA50001.getDesc(), e);
    }
}

From source file:org.kurento.test.base.BrowserTest.java

public void waitForHostIsReachable(URL url, int timeout) {
    long timeoutMillis = TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
    long endTimeMillis = System.currentTimeMillis() + timeoutMillis;

    log.debug("Waiting for {} to be reachable (timeout {} seconds)", url, timeout);

    try {//from  w w  w .j av a2 s. c om
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

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

        int responseCode = 0;
        while (true) {
            try {
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout((int) timeoutMillis);
                connection.setReadTimeout((int) timeoutMillis);
                connection.setRequestMethod("HEAD");
                responseCode = connection.getResponseCode();

                break;
            } catch (SSLHandshakeException | SocketException e) {
                log.warn("Error {} waiting URL {}, trying again in 1 second", e.getMessage(), url);
                // Polling to wait a consistent SSL state
                Thread.sleep(1000);
            }
            if (System.currentTimeMillis() > endTimeMillis) {
                break;
            }
        }

        if (responseCode != HttpURLConnection.HTTP_OK) {
            log.warn("URL " + url + " not reachable. Response code=" + responseCode);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("URL " + url + " not reachable in " + timeout + " seconds (" + e.getClass().getName() + ", "
                + e.getMessage() + ")");
    }

    log.debug("URL {} already reachable", url);
}

From source file:code.google.restclient.core.Hitter.java

private TrustManager getNoCheckTrustManager() {
    return new X509TrustManager() {
        @Override//from   www  . j ava2s.  c  om
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Do nothing
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Do nothing
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
}

From source file:com.createtank.payments.coinbase.RequestClient.java

public static void disableCertificateValidation() {
    // 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 w  w . ja v  a  2  s .co 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) {
        //Ignore
    }
}

From source file:io.kodokojo.brick.gitlab.GitlabConfigurer.java

public static OkHttpClient provideDefaultOkHttpClient() {
    OkHttpClient httpClient = new OkHttpClient();
    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override//from  www  .  j a v a  2s. c o  m
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ex) {
        //
    }
    httpClient.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    httpClient.setSslSocketFactory(ctx.getSocketFactory());
    CookieManager cookieManager = new CookieManager(new GitlabCookieStore(), CookiePolicy.ACCEPT_ALL);
    httpClient.setCookieHandler(cookieManager);
    httpClient.setReadTimeout(2, TimeUnit.MINUTES);
    httpClient.setConnectTimeout(1, TimeUnit.MINUTES);
    httpClient.setWriteTimeout(1, TimeUnit.MINUTES);
    return httpClient;
}

From source file:ilarkesto.net.ApacheHttpDownloader.java

private HttpClient wrapClientForDisabledServerChecking(HttpClient client) {
    try {/*from w w  w. ja  va  2s. co m*/
        X509TrustManager tm = new X509TrustManager() {

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

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

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

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java

/**
 * Create basic SSL connection factory//w w  w. ja v a 2s.  co  m
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {

                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:org.jboss.as.test.integration.management.api.web.ConnectorTestCase.java

public static HttpClient wrapClient(HttpClient base) {
    try {//from  w  ww  .  jav  a2 s  . c o m
        SSLContext ctx = SSLContext.getInstance("TLS");
        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;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_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;
    }
}