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.example.bbbbbb.http.sample.util.SecureSocketFactory.java

/**
 * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the
 * store with the password using {@link KeyStore#load(InputStream,
 * char[])} method./*  w ww.  j ava 2 s .com*/
 *
 * @param store The key store holding the certificate details
 * @param alias The alias of the certificate to use
 */
public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(store);

    // Loading the CA certificate from store.
    final Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    AsyncHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Embedded SSL certificate has expired.");
    }

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid.");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid.");
            } else {
                Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates.");
                try {
                    for (X509Certificate cert : chain) {
                        Log.i(LOG_TAG, "Server Certificate Details:");
                        Log.i(LOG_TAG, "---------------------------");
                        Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                        Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                        Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                        Log.i(LOG_TAG, "Version: " + cert.getVersion());
                        Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                        Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                        Log.i(LOG_TAG, "---------------------------");

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's public key chain.
                        cert.verify(rootca.getPublicKey());
                    }
                } catch (InvalidKeyException e) {
                    error = e;
                } catch (NoSuchAlgorithmException e) {
                    error = e;
                } catch (NoSuchProviderException e) {
                    error = e;
                } catch (SignatureException e) {
                    error = e;
                }
            }
            if (null != error) {
                Log.e(LOG_TAG, "Certificate error", error);
                throw new CertificateException(error);
            }
        }

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

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:net.bluemix.newsaggregator.api.AuthenticationServlet.java

static public void configureSSL() {
    // note that it's not adviced to use this in a production application
    // you should overwrite the X509TrustManager to use a cacerts file (list of trusted signers) 
    try {//  w ww  .  ja v a 2s.co m
        SSLContext sslContext = SSLContext.getInstance("SSL_TLSv2");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

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

        Executor.unregisterScheme("https");
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Executor.registerScheme(new Scheme("https", 443, sslSocketFactory));

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:fr.wseduc.webdav.WebDav.java

private Sardine getSardine(String uri, Message<JsonObject> message) {
    String host;/*from www  .  ja v a2s.c om*/
    try {
        host = new URI(uri).getHost();
    } catch (URISyntaxException e) {
        sendError(message, e.getMessage(), e);
        return null;
    }
    JsonObject credential = credentials.getJsonObject(host);
    Sardine sardine;
    if (credential != null) {
        if (credential.getBoolean("insecure", false)) {
            sardine = new SardineImpl() {
                @Override
                protected ConnectionSocketFactory createDefaultSecureSocketFactory() {
                    SSLConnectionSocketFactory sf = null;
                    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

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

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                                String authType) {
                        }
                    } };
                    try {
                        SSLContext context = SSLContext.getInstance("TLS");
                        context.init(null, trustAllCerts, null);

                        sf = new SSLConnectionSocketFactory(context,
                                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                    } catch (NoSuchAlgorithmException | KeyManagementException e) {
                        logger.error(e.getMessage(), e);
                    }
                    return sf;
                }
            };
            sardine.setCredentials(credential.getString("username"), credential.getString("password"));
        } else {
            sardine = SardineFactory.begin(credential.getString("username"), credential.getString("password"));
        }
        sardine.enablePreemptiveAuthentication(host);
    } else {
        sardine = SardineFactory.begin();
    }
    return sardine;
}

From source file:org.wso2.extension.siddhi.device.utils.ClientUtils.java

public static OkHttpClient getSSLClient() {

    boolean isIgnoreHostnameVerification = Boolean
            .parseBoolean(System.getProperty("org.wso2" + ".ignoreHostnameVerification"));
    OkHttpClient okHttpClient;/*from  ww  w .  j  a v a 2s  . co  m*/
    final String proxyHost = System.getProperty("http.proxyHost");
    final String proxyPort = System.getProperty("http.proxyPort");
    final String nonProxyHostsValue = System.getProperty("http.nonProxyHosts");

    final ProxySelector proxySelector = new ProxySelector() {
        @Override
        public List<Proxy> select(URI uri) {
            List<Proxy> proxyList = new ArrayList<>();
            String host = uri.getHost();

            if (!StringUtils.isEmpty(host)) {
                if (host.startsWith(DEFAULT_HOST_IP) || host.startsWith(DEFAULT_HOST)
                        || StringUtils.isEmpty(nonProxyHostsValue)
                        || StringUtils.contains(nonProxyHostsValue, host) || StringUtils.isEmpty(proxyHost)
                        || StringUtils.isEmpty(proxyPort)) {
                    proxyList.add(Proxy.NO_PROXY);
                } else {
                    proxyList.add(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))));
                }
            } else {
                log.error("Host is null. Host could not be empty or null");
            }
            return proxyList;
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    };

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

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

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    };
    if (isIgnoreHostnameVerification) {
        okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }).proxySelector(proxySelector).build();
        return okHttpClient;
    } else {
        SSLSocketFactory trustedSSLSocketFactory = getTrustedSSLSocketFactory();
        okHttpClient = new OkHttpClient.Builder().sslSocketFactory(trustedSSLSocketFactory)
                .proxySelector(proxySelector).build();
        return okHttpClient;
    }
}

From source file:es.tsb.ltba.nomhad.example.ClientWithResponseHandler.java

private static DefaultHttpClient wrapClient(HttpClient base) {
    try {/*  w ww  . j ava  2s.  c  om*/
        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, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java

private void trustAll() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from  w w  w.  j  av  a 2 s . c  om
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

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

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

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        System.out.println("Oops");
    }
}

From source file:co.cask.cdap.security.server.ExternalAuthenticationServerSSLTest.java

@Override
protected HttpClient getHTTPClient() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override//from www . ja v  a2s.c o m
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                throws CertificateException {
            //
        }

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

    } }, new SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    Scheme httpsScheme = new Scheme("https", getAuthServerPort(), sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    // apache HttpClient version >4.2 should use BasicClientConnectionManager
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
    return new DefaultHttpClient(cm);
}

From source file:org.openmuc.framework.driver.rest.RestConnection.java

public RestConnection(String deviceAddress, String credentials, int timeout) throws ConnectionException {

    this.timeout = timeout;
    wrapper = new JsonWrapper();
    authString = new String(Base64.encodeBase64(credentials.getBytes()));

    if (!deviceAddress.endsWith("/")) {
        this.deviceAddress = deviceAddress + "/channels/";
    } else {//w  w w  .j  a  va 2  s. c o  m
        this.deviceAddress = deviceAddress + "channels/";
    }

    if (deviceAddress.startsWith("https://")) {
        isHTTPS = true;
    } else {
        isHTTPS = false;
    }

    if (isHTTPS) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

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

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (KeyManagementException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        // HttpsURLConnection.setFollowRedirects(false);
    }
}

From source file:com.saylor.harrison.opustestround2.audio.WebSocketUploader.java

/**
 * Trust server// www  . j  a v a 2s  . c o m
 *
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private void trustServer() throws KeyManagementException, NoSuchAlgorithmException, IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

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

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext sslContext = null;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, certs, new java.security.SecureRandom());
    SSLSocketFactory factory = sslContext.getSocketFactory();
    this.setSocket(factory.createSocket());
}