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:com.marklogic.client.functionaltest.TestSSLConnection.java

@Test
public void testSSLConnectionInvalidUser()
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    System.out.println("Running testSSLConnectionInvalidUser");

    String filename = "facebook-10443244874876159931";

    // create a trust manager
    // (note: a real application should verify certificates)
    TrustManager naiveTrustMgr = new X509TrustManager() {
        @Override// w  w  w. j a v a 2  s .  c o  m
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

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

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

    // create an SSL context
    SSLContext sslContext = SSLContext.getInstance("SSLv3");
    sslContext.init(null, new TrustManager[] { naiveTrustMgr }, null);

    // create the client
    // (note: a real application should use a COMMON, STRICT, or implemented hostname verifier)
    DatabaseClient client = DatabaseClientFactory.newClient("localhost", 8012, "MyFooUser", "x",
            Authentication.DIGEST, sslContext, SSLHostnameVerifier.ANY);

    String expectedException = "FailedRequestException: Local message: write failed: Unauthorized";
    String exception = "";

    // write doc
    try {
        writeDocumentUsingStringHandle(client, filename, "/write-text-doc/", "Text");
    } catch (Exception e) {
        exception = e.toString();
    }

    boolean isExceptionThrown = exception.contains(expectedException);

    assertTrue("Exception is not thrown", isExceptionThrown);

    // release client
    client.release();
}

From source file:org.jenkinsci.plugins.codefresh.CFApi.java

private void secureContext(boolean selfSignedCert) {
    this.https = true;
    trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*w  w  w . jav a2 s . c  o m*/

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

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

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        this.sf = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(this.sf);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
    if (selfSignedCert) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession sslSession) {
                return true;
            }
        });
    }
}

From source file:com.arm.connector.bridge.transport.HttpTransport.java

@SuppressWarnings("empty-statement")
private String doHTTP(String verb, String url_str, String username, String password, String data,
        String content_type, String auth_domain, boolean doInput, boolean doOutput, boolean doSSL,
        boolean use_api_token, String api_token) {
    String result = "";
    String line = "";
    URLConnection connection = null;
    SSLContext sc = null;//  ww  w.j a  v  a2 s .com

    try {
        URL url = new URL(url_str);

        // Http Connection and verb
        if (doSSL) {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = 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) {
                }
            } };

            // Install the all-trusting trust manager
            try {
                sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                // do nothing
                ;
            }

            // open the SSL connction
            connection = (HttpsURLConnection) (url.openConnection());
            ((HttpsURLConnection) connection).setRequestMethod(verb);
            ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } else {
            connection = (HttpURLConnection) (url.openConnection());
            ((HttpURLConnection) connection).setRequestMethod(verb);
        }

        connection.setDoInput(doInput);
        if (doOutput && data != null && data.length() > 0) {
            connection.setDoOutput(doOutput);
        } else {
            connection.setDoOutput(false);
        }

        // enable basic auth if requested
        if (use_api_token == false && username != null && username.length() > 0 && password != null
                && password.length() > 0) {
            String encoding = Base64.encodeBase64String((username + ":" + password).getBytes());
            connection.setRequestProperty("Authorization", this.m_basic_auth_qualifier + " " + encoding);
            //this.errorLogger().info("Basic Authorization: " + username + ":" + password + ": " + encoding);
        }

        // enable ApiTokenAuth auth if requested
        if (use_api_token == true && api_token != null && api_token.length() > 0) {
            // use qualification for the authorization header...
            connection.setRequestProperty("Authorization", this.m_auth_qualifier + " " + api_token);
            //this.errorLogger().info("ApiTokenAuth Authorization: " + api_token);

            // Always reset to the established default
            this.resetAuthorizationQualifier();
        }

        // ETag support if requested
        if (this.m_etag_value != null && this.m_etag_value.length() > 0) {
            // set the ETag header value
            connection.setRequestProperty("ETag", this.m_etag_value);
            //this.errorLogger().info("ETag Value: " + this.m_etag_value);

            // Always reset to the established default
            this.resetETagValue();
        }

        // If-Match support if requested
        if (this.m_if_match_header_value != null && this.m_if_match_header_value.length() > 0) {
            // set the If-Match header value
            connection.setRequestProperty("If-Match", this.m_if_match_header_value);
            //this.errorLogger().info("If-Match Value: " + this.m_if_match_header_value);

            // Always reset to the established default
            this.resetIfMatchValue();
        }

        // specify content type if requested
        if (content_type != null && content_type.length() > 0) {
            connection.setRequestProperty("Content-Type", content_type);
            connection.setRequestProperty("Accept", "*/*");
        }

        // add Connection: keep-alive (does not work...)
        //connection.setRequestProperty("Connection", "keep-alive");

        // special gorp for HTTP DELETE
        if (verb != null && verb.equalsIgnoreCase("delete")) {
            connection.setRequestProperty("Access-Control-Allow-Methods", "OPTIONS, DELETE");
        }

        // specify domain if requested
        if (auth_domain != null && auth_domain.length() > 0) {
            connection.setRequestProperty("Domain", auth_domain);
        }

        // DEBUG dump the headers
        //if (doSSL) 
        //    this.errorLogger().info("HTTP: Headers: " + ((HttpsURLConnection)connection).getRequestProperties()); 
        //else
        //    this.errorLogger().info("HTTP: Headers: " + ((HttpURLConnection)connection).getRequestProperties()); 

        // specify data if requested - assumes it properly escaped if necessary
        if (doOutput && data != null && data.length() > 0) {
            try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())) {
                out.write(data);
            }
        }

        // setup the output if requested
        if (doInput) {
            try {
                try (InputStream content = (InputStream) connection.getInputStream();
                        BufferedReader in = new BufferedReader(new InputStreamReader(content))) {
                    while ((line = in.readLine()) != null) {
                        result += line;
                    }
                }
            } catch (java.io.FileNotFoundException ex) {
                this.errorLogger().info("HTTP(" + verb + ") empty response (OK).");
                result = "";
            }
        } else {
            // no result expected
            result = "";
        }

        // save off the HTTP response code...
        if (doSSL)
            this.saveResponseCode(((HttpsURLConnection) connection).getResponseCode());
        else
            this.saveResponseCode(((HttpURLConnection) connection).getResponseCode());

        // DEBUG
        //if (doSSL)
        //    this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpsURLConnection)connection).getResponseCode());
        //else
        //    this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpURLConnection)connection).getResponseCode());
    } catch (IOException ex) {
        this.errorLogger().warning("Caught Exception in doHTTP(" + verb + "): " + ex.getMessage());
        result = null;
    }

    // return the result
    return result;
}

From source file:com.aliyun.api.gateway.demo.util.HttpUtil.java

private static void sslClient(HttpClient httpClient) {
    try {//from w ww  .j ava 2 s .co m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] xcs, String str) {

            }

            public void checkServerTrusted(X509Certificate[] xcs, String str) {

            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry registry = ccm.getSchemeRegistry();
        registry.register(new Scheme("https", 443, ssf));
    } catch (KeyManagementException ex) {
        throw new RuntimeException(ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:cn.tc.ulife.platform.msg.http.util.HttpUtil.java

private static void sslClient(HttpClient httpClient) {
    try {//  w  w  w  .  java 2  s . co  m
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] xcs, String str) {

            }

            public void checkServerTrusted(X509Certificate[] xcs, String str) {

            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry registry = ccm.getSchemeRegistry();
        registry.register(new Scheme("https", ssf, 443));
    } catch (KeyManagementException ex) {
        throw new RuntimeException(ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.chaosinmotion.securechat.messages.SCMessageQueue.java

/**
 * The back end is advertising an endpoint we can connect to for
 * asynchronous networking. Attempt to open a connection. Note that
 * this must be kicked off in a background thread.
 *///from   ww w.j a v  a2s.c o  m

private void openConnection(String host, int port, boolean ssl)
        throws NoSuchAlgorithmException, KeyManagementException, IOException, JSONException {
    if (ssl) {
        TrustManager acceptAllTrustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

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

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        TrustManager[] tm = new TrustManager[] { acceptAllTrustManager };
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], tm, new SecureRandom());

        SSLSocketFactory factory = context.getSocketFactory();

        socket = factory.createSocket(host, port);
    } else {
        socket = new Socket(host, port);
    }

    /*
     *  Kick off an output stream
     */

    output = new SCOutputStream(socket.getOutputStream());

    /*
     *  Kick off a thread to process the input stream
     */

    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                input = new SCInputStream(socket.getInputStream()) {
                    @Override
                    public void processPacket(byte[] data) {
                        processDataPacket(data);
                    }
                };
                input.processStream();
                input.close();

                /*
                 *  When the input closes, we simply quit the thread.
                 *  TODO: I'm not sure if that's the correct answer.
                 */
            } catch (final Exception ex) {
                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        startPolling("Unknown exception " + ex.getMessage());
                        Log.d("SecureChat", "Exception while opening socket", ex);
                    }
                });
            }
        }
    };
    thread.start();

    /*
     *   Now the first packet we need to send to the writer (and our
     *   output stream will cache this) is a JSON request to log in.
     *
     *   On the off chance logging in fails, the back end will simply
     *   close the connection.
     *
     *   Because there is no one-to-one (in theory) of data sent and
     *   received, we drive this through a state machine.
     */

    JSONObject obj = new JSONObject();
    obj.put("cmd", "token");
    byte[] data = obj.toString().getBytes("UTF-8");
    output.writeData(data);
}

From source file:net.fenyo.mail4hotspot.service.MailManager.java

public static void trustSSL() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from  ww w .ja  v  a2 s  .c  o m*/

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

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

    // c'est un pb de scurit, il faudrait mettre  jour les certifs racine et supprimer le all-trusting trust manager
    // 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) {
        System.out.println("Can not install the all-trusting trust manager");
    }
}

From source file:org.brunocvcunha.taskerbox.core.http.TaskerboxHttpBox.java

/**
 * Default Trust Manager that trusts all certs
 *
 * @return//from w  w w  .jav  a 2s.com
 */
private TrustManager[] getTrustingManager() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    } };
    return trustAllCerts;
}

From source file:com.wudaosoft.net.httpclient.Request.java

protected void init() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
        CertificateException, IOException {

    Args.notNull(hostConfig, "Host config");

    SSLConnectionSocketFactory sslConnectionSocketFactory = null;

    if (sslcontext == null) {

        if (hostConfig.getCA() != null) {
            // Trust root CA and all self-signed certs
            SSLContext sslcontext1 = SSLContexts.custom().loadTrustMaterial(hostConfig.getCA(),
                    hostConfig.getCAPassword(), TrustSelfSignedStrategy.INSTANCE).build();

            // Allow TLSv1 protocol only
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1, new String[] { "TLSv1" },
                    null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        } else {//  w  ww . j a  v  a  2s  .  com

            if (isTrustAll) {

                SSLContext sslcontext1 = SSLContext.getInstance("TLS");

                TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                            throws CertificateException {
                    }

                } };

                sslcontext1.init(null, trustAllCerts, null);

                sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext1,
                        NoopHostnameVerifier.INSTANCE);
            } else {
                sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            }
        }
    } else {

        sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    }

    if (keepAliveStrategy == null) {
        keepAliveStrategy = new ConnectionKeepAliveStrategy() {

            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                // Honor 'keep-alive' header
                HeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch (NumberFormatException ignore) {
                        }
                    }
                }
                // HttpHost target = (HttpHost)
                // context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
                // if
                // ("xxxxx".equalsIgnoreCase(target.getHostName()))
                // {
                // // Keep alive for 5 seconds only
                // return 3 * 1000;
                // } else {
                // // otherwise keep alive for 30 seconds
                // return 30 * 1000;
                // }

                return 30 * 1000;
            }

        };
    }

    if (retryHandler == null) {
        retryHandler = new HttpRequestRetryHandler() {

            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 3) {
                    // Do not retry if over max retry count
                    return false;
                }
                if (exception instanceof InterruptedIOException) {
                    // Timeout
                    return false;
                }
                if (exception instanceof UnknownHostException) {
                    // Unknown host
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {
                    // Connection refused
                    return false;
                }
                if (exception instanceof SSLException) {
                    // SSL handshake exception
                    return false;
                }
                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                if (idempotent) {
                    // Retry if the request is considered idempotent
                    return true;
                }
                return false;
            }
        };
    }

    connManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslConnectionSocketFactory).build());

    if (hostConfig.getHost() != null) {

        connManager.setMaxTotal(hostConfig.getPoolSize() + 60);

        connManager.setMaxPerRoute(
                new HttpRoute(hostConfig.getHost(), null,
                        !HttpHost.DEFAULT_SCHEME_NAME.equals(hostConfig.getHost().getSchemeName())),
                hostConfig.getPoolSize());

        connManager.setDefaultMaxPerRoute(20);
    } else {
        connManager.setMaxTotal(hostConfig.getPoolSize());
        int hostCount = hostConfig.getHostCount() == 0 ? 10 : hostConfig.getHostCount();
        connManager.setDefaultMaxPerRoute(hostConfig.getPoolSize() / hostCount);
    }

    // connManager.setValidateAfterInactivity(2000);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(isKeepAlive).build();
    connManager.setDefaultSocketConfig(socketConfig);

    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(hostConfig.getCharset() == null ? Consts.UTF_8 : hostConfig.getCharset()).build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    new IdleConnectionMonitorThread(connManager).start();

    if (requestInterceptor == null) {
        requestInterceptor = new SortHeadersInterceptor(hostConfig);
    }

    if (!hostConfig.isMulticlient()) {
        defaultHttpContext = HttpClientContext.create();
        httpClient = create();
    }
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@SuppressWarnings("deprecation")
@Test//  w ww .  j  av  a 2s . c  o  m
public void testSSLConnection() throws Exception {
    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLSocketFactory ssf = new SSLSocketFactory(SSLContext.getInstance("TLS"));
    ssf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", ssf, 443);
    SchemeRegistry sr = new SchemeRegistry();
    sr.register(http);
    sr.register(https);

    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
            System.out.println("checkClientTrusted");
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
            System.out.println("checkServerTrusted");
        }

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

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    SSLSocket socket = (SSLSocket) sf.createSocket();
    socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
    sf.connectSocket(socket, "119.29.234.42", 443, null, -1, params);
}