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.sakuli.services.forwarder.icinga2.Icinga2RestCient.java

private SSLContext getTrustEverythingSSLContext() {
    try {/*from  w w  w  .j  ava 2  s  .  c  o  m*/
        final SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } }, new SecureRandom());
        return sslContext;
    } catch (Exception e) {
        throw new SakuliRuntimeException("Unable to create SSL-Context", e);
    }
}

From source file:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Creates a new SSL Socket Factory with the given KeyStore.
 *
 * @param truststore A KeyStore to create the SSL Socket Factory in context of
 * @throws NoSuchAlgorithmException  NoSuchAlgorithmException
 * @throws KeyManagementException    KeyManagementException
 * @throws KeyStoreException         KeyStoreException
 * @throws UnrecoverableKeyException UnrecoverableKeyException
 *//*  w  w w  . ja  va 2  s  . c o  m*/
public MySSLSocketFactory(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(truststore);

    X509TrustManager tm = 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.init(null, new TrustManager[] { tm }, null);
}

From source file:com.ovea.facebook.client.DefaultFacebookClient.java

public DefaultFacebookClient(String client_id, String client_secret, String redirect_uri) {
    this.clientId = client_id;
    this.clientSecret = client_secret;
    this.redirectUri = redirect_uri;
    try {/*from ww  w . ja v  a 2  s.c o m*/
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
        sslSocketFactory = new SSLSocketFactory(sslContext);
        //noinspection deprecation
        sslSocketFactory.setHostnameVerifier(new X509HostnameVerifier() {
            @Override
            public void verify(String host, SSLSocket ssl) throws IOException {
            }

            @Override
            public void verify(String host, X509Certificate cert) throws SSLException {
            }

            @Override
            public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
            }

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (NoSuchAlgorithmException e) {
        throw new FacebookException(e.getMessage(), e);
    } catch (KeyManagementException e) {
        throw new FacebookException(e.getMessage(), e);
    }
}

From source file:com.devoteam.srit.xmlloader.http.bio.BIOChannelHttp.java

/** Open a connexion to each Stack */
public boolean open() throws Exception {
    if (this.secure) {
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TLS,
                StackFactory.PROTOCOL_HTTP);
    } else {/*from   w  w  w  .j a v a2s. c o  m*/
        StatPool.beginStatisticProtocol(StatPool.CHANNEL_KEY, StatPool.BIO_KEY, StackFactory.PROTOCOL_TCP,
                StackFactory.PROTOCOL_HTTP);
    }

    this.startTimestamp = System.currentTimeMillis();

    if (null != this.socketServerHttp) {
        ThreadPool.reserve().start((BIOSocketServerHttp) socketServerHttp);
    } else {

        String host = this.getRemoteHost();
        int port = this.getRemotePort();

        DefaultHttpClientConnection defaultHttpClientConnection = new DefaultHttpClientConnection();

        Socket socket;

        if (this.secure) {
            // Create a trust manager that does not validate certificate chains like the default TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }

                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    //No need to implement.
                }
            } };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, null);

            socket = sslContext.getSocketFactory().createSocket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, true);
        } else {
            //
            // Create a TCP non secure socket
            //                
            socket = new Socket();
            // read all properties for the TCP socket 
            Config.getConfigForTCPSocket(socket, false);
        }

        //
        // Bind the socket to the local address
        //
        String localHost = this.getLocalHost();
        int localPort = initialLocalport;

        if (null != localHost) {
            socket.bind(new InetSocketAddress(localHost, localPort));
        } else {
            socket.bind(new InetSocketAddress(localPort));
        }

        socket.setReceiveBufferSize(65536);
        socket.connect(new InetSocketAddress(host, port));

        this.setLocalPort(socket.getLocalPort());

        HttpParams params = new BasicHttpParams();
        defaultHttpClientConnection.bind(socket, params);

        this.socketClientHttp = new BIOSocketClientHttp(defaultHttpClientConnection, this);

        ThreadPool.reserve().start((BIOSocketClientHttp) socketClientHttp);
    }
    return true;
}

From source file:org.cloudifysource.restclient.RestSSLSocketFactory.java

public RestSSLSocketFactory(final KeyStore trustStore, final X509HostnameVerifier hostnameVarifier)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(null, null, null, trustStore, null, hostnameVarifier);

    TrustManager tm = new X509TrustManager() {
        @Override/*  ww  w .  ja v  a 2 s  . com*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub

        }

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

        }
    };

    sslContext.init(null, new TrustManager[] { tm }, null);
}

From source file:guru.mmp.common.http.SecureHttpClientBuilder.java

private synchronized SSLConnectionSocketFactory getSSLConnectionSocketFactory() {
    if (sslSocketFactory == null) {
        try {/*from   w ww  . jav a  2  s .  c o m*/
            SSLContext sslContext = SSLContext.getInstance("TLS");

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Skip client verification step
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    if (serverValidationEnabled) {
                        // TODO: Implement server certificate validation
                    }
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };

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

            sslSocketFactory = new SSLConnectionSocketFactory(sslContext.getSocketFactory(),
                    new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession sslSession) {
                            if (serverValidationEnabled) {
                                // TODO: Implement proper verification of the server identity -- MARCUS
                            }

                            return true;

                            // if (hostname.equalsIgnoreCase(sslSession.getPeerHost()))
                            // {
                            // return true;
                            // }
                            // else
                            // {
                            // logger.error("Failed to verify the SSL connection to the host ("
                            // + hostname + ") which returned a certificate for the host (" + sslSession.getPeerHost() + ")");
                            //
                            // return false;
                            // }
                        }
                    });
        } catch (Throwable e) {
            throw new RuntimeException("Failed to create the no-trust SSL socket factory", e);
        }
    }

    return sslSocketFactory;
}

From source file:it.zero11.acme.Acme.java

private static SSLContext getTrustAllCertificateSSLContext()
        throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from  ww w  .j  av  a2s. co m
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

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

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

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    return sc;
}

From source file:eu.itesla_project.histodb.client.impl.HistoDbHttpClientImpl.java

private synchronized CloseableHttpClient getHttpclient(HistoDbConfig config) {
    if (httpClient == null) {
        try {//from w  w  w. j  ava 2s.c o m
            ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
            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 sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", plainsf).register("https", sslsf).build();
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
            cm.setDefaultMaxPerRoute(10);
            cm.setMaxTotal(20);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(cm);
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(
                    new AuthScope(new HttpHost(config.getConnectionParameters().getHost(),
                            config.getConnectionParameters().getPort())),
                    new UsernamePasswordCredentials(config.getConnectionParameters().getUserName(),
                            config.getConnectionParameters().getPassword()));
            if (config.getProxyParameters() != null) {
                HttpHost proxy = new HttpHost(config.getProxyParameters().getHost(),
                        config.getProxyParameters().getPort());
                credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(
                        config.getProxyParameters().getUserName(), config.getProxyParameters().getPassword()));
                httpClientBuilder.setProxy(proxy);
            }
            httpClient = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).build();
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    return httpClient;
}

From source file:org.appverse.web.framework.backend.ws.helpers.StubHelper.java

public static void configureEndpoint(String endpointPropertiesFile, String timeoutPropertyName,
        ServiceClient _serviceClient) {/*from  w w  w  .j  a v a2s.c om*/
    Properties endpointsProperties = new Properties();
    InputStream endPointsInputStream = StubHelper.class.getResourceAsStream(endpointPropertiesFile);
    try {
        endpointsProperties.load(endPointsInputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String accountTimeoutString = (String) endpointsProperties.get(timeoutPropertyName);
    try {
        long accountTimeout = new Long(accountTimeoutString) * 1000;
        _serviceClient.getOptions().setTimeOutInMilliSeconds(accountTimeout);
    } catch (NumberFormatException e) {
        logger.equals("Error login axis account service timeout");
    }
    String endpointProxyEnabled = (String) endpointsProperties.get("endpoint.proxy.enabled");
    if (endpointProxyEnabled != null && endpointProxyEnabled.equals("true")) {
        HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
        String endpointProxyHost = endpointsProperties.getProperty("endpoint.proxy.host");
        proxyProperties.setProxyName(endpointProxyHost);
        int endpointProxyPort = new Integer(endpointsProperties.getProperty("endpoint.proxy.port"));
        proxyProperties.setProxyPort(endpointProxyPort);
        _serviceClient.getOptions().setProperty(HTTPConstants.PROXY, proxyProperties);
    }
    if (endpointsProperties.getProperty("endpoint.ignore_SSL_errors") != null
            && endpointsProperties.getProperty("endpoint.ignore_SSL_errors").equals("true")) {
        // Create a trust manager that does not validate certificate
        // chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

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

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

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

    ConfigurationContext configurationContext = _serviceClient.getServiceContext().getConfigurationContext();
    MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setDefaultMaxConnectionsPerHost(50);
    multiThreadedHttpConnectionManager.setParams(params);
    HttpClient httpClient = new HttpClient(multiThreadedHttpConnectionManager);
    configurationContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);

}

From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java

public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            // System.out.println("getAcceptedIssuers =============");
            return null;
        }/*from  w  ww.  jav a  2  s .co  m*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkClientTrusted =============");
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // System.out.println("checkServerTrusted =============");
        }
    } }, new SecureRandom());

    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
            .setRedirectStrategy(new DefaultRedirectStrategy() {
                @Override
                protected boolean isRedirectable(String arg0) {
                    // TODO Auto-generated method stub
                    return super.isRedirectable(arg0);
                }

                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    // TODO Auto-generated method stub
                    return super.isRedirected(request, response, context);
                }
            }).setDefaultCookieStore(new BasicCookieStore())
            .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0")
            .build();

    Executor exec = Executor.newInstance(httpclient);

    URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html");

    String fullURL = ub.build().toASCIIString();
    Request req = HttpUtils.get(fullURL, sp);
    HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    String tgtID = readData(exec, req, monitor);
    String action = getFormAction(tgtID);
    if (action != null) {
        action = action.replaceFirst("/", "");
        int indx = action.indexOf(";jsession");
        if (indx >= 0)
            action = action.substring(0, indx);
    } else
        action = "cas/login";
    String url = srv.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub = new URIBuilder(url + action);
    //
    fullURL = ub.build().toASCIIString();
    req = HttpUtils.get(fullURL, sp);
    proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL));
    if (proxy != null)
        req.viaProxy(proxy);
    tgtID = readData(exec, req, monitor);
    action = getFormAction(tgtID);
    action = action.replaceFirst("/", "");

    ub = new URIBuilder(url + action);
    Map<String, String> map = getInputs(tgtID);
    Form form = Form.form();
    for (String key : map.keySet()) {
        if (key.equals("btn-reset"))
            continue;
        else if (key.equals("username")) {
            form.add(key, srv.getUser());
            continue;
        } else if (key.equals("password")) {
            form.add(key, Pass.getPass(srv.getPassword()));
            continue;
        }
        form.add(key, map.get(key));
    }
    //
    req = HttpUtils.post(ub.build().toASCIIString(), form, sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // Header header = null;
    readData(exec, req, monitor);
    // for (Header h : headers) {
    // for (HeaderElement he : h.getElements()) {
    // if (he.getName().equals("CASTGC")) {
    // header = new BasicHeader("Cookie", h.getValue());
    // break;
    // }
    // }
    // }
    ub = new URIBuilder(url + action);
    url = sp.getUrl();
    if (!url.endsWith("/"))
        url += "/";
    ub.addParameter("service", url + "j_spring_security_check");

    req = HttpUtils.get(ub.build().toASCIIString(), sp);
    if (proxy != null)
        req.viaProxy(proxy);
    // req.addHeader("Accept",
    // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value");
    req.addHeader("Referrer", sp.getUrl());
    // req.addHeader(header);
    String html = readData(exec, req, monitor);
    Matcher matcher = ahrefPattern.matcher(html);
    while (matcher.find()) {
        Map<String, String> attributes = parseAttributes(matcher.group(1));
        String v = attributes.get("href");
        int ind = v.indexOf("ticket=");
        if (ind > 0) {
            return v.substring(ind + "ticket=".length());
        }
    }
    return null;
}