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:it.anyplace.sync.core.security.KeystoreHandler.java

private SSLSocketFactory getSocketFactory()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    SSLContext sslContext = SSLContext.getInstance(TLS_VERSION);
    sslContext.init(getKeyManagers(), new TrustManager[] { new X509TrustManager() {
        @Override/*  w  ww  . ja v a 2  s .c  o  m*/
        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;
        }
    } }, null);
    return sslContext.getSocketFactory();
}

From source file:edu.duke.cabig.c3pr.webservice.integration.C3PREmbeddedTomcatTestBase.java

/**
 * Code of this method was simply Googled.
 */// w  ww  .j  a  v  a 2 s . co  m
void disableSSLVerification() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

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

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

        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 (Exception e) {
        e.printStackTrace();
    }

    com.sun.net.ssl.HostnameVerifier hv = new com.sun.net.ssl.HostnameVerifier() {

        public boolean verify(String urlHostname, String certHostname) {
            return true;
        }
    };
    com.sun.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);

    HostnameVerifier hv2 = new HostnameVerifier() {

        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv2);

}

From source file:org.eclipse.lyo.testsuite.server.util.OSLCUtils.java

static public void setupLazySSLSupport(HttpClient httpClient) {
    ClientConnectionManager connManager = httpClient.getConnectionManager();
    SchemeRegistry schemeRegistry = connManager.getSchemeRegistry();
    schemeRegistry.unregister("https");
    /** Create a trust manager that does not validate certificate chains */
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }/* w ww  .  j ava  2 s. co  m*/

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            /** Ignore Method Call */
        }

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

    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        /* Fail Silently */
    } catch (KeyManagementException e) {
        /* Fail Silently */
    }

    SSLSocketFactory sf = new SSLSocketFactory(sc);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    schemeRegistry.register(https);
}

From source file:org.apache.openmeetings.web.pages.auth.SignInPage.java

private static void prepareConnection(URLConnection connection) {
    if (!(connection instanceof HttpsURLConnection))
        return;//from   w  w  w.ja v  a2s  .  c o m
    ConfigurationDao configurationDao = getBean(ConfigurationDao.class);
    Boolean ignoreBadSSL = configurationDao.getConfValue(CONFIG_IGNORE_BAD_SSL, String.class, "no")
            .equals("yes");
    if (!ignoreBadSSL)
        return;
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

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

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

    } };
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

        });
    } catch (Exception e) {
        log.error("[prepareConnection]", e);
    }
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

private X509TrustManager getCustomTrustManager(final X509TrustManager defaultTrustManager,
        final KeystoreConfig keystoreConfig, final boolean acceptUnverifiedCertificates,
        final KeyStore trustStore) {
    return new X509TrustManager() {
        private final Log log = LogFactory.getLog(X509TrustManager.class);

        public X509Certificate[] getAcceptedIssuers() {
            return defaultTrustManager.getAcceptedIssuers();
        }//from  w  w w. ja  v a 2s . com

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                defaultTrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException e) {
                CertificateExpiredException expiredCertException = getCertExpiredException(e);
                if (expiredCertException != null) {
                    log.error("Fail the connection because received certificate is expired. "
                            + "Please update the certificate.", expiredCertException);
                    throw new CertificateException(e);
                }
                if (acceptUnverifiedCertificates) {
                    log.info("Import the certification. (Received certificate is not trusted by keystore)");
                    importCertificate(chain);
                } else {
                    log.warn(
                            "Fail the connection because received certificate is not trusted by keystore: alias="
                                    + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath());
                    log.debug(
                            "Fail the connection because received certificate is not trusted by keystore: alias="
                                    + keystoreConfig.getAlias() + ", path=" + keystoreConfig.getFilePath()
                                    + ", acceptUnverifiedCertificates=" + acceptUnverifiedCertificates,
                            e);
                    throw new CertificateException(e);
                }
            }
        }

        private CertificateExpiredException getCertExpiredException(Exception e) {
            while (e != null) {
                if (e instanceof CertificateExpiredException) {
                    return (CertificateExpiredException) e;
                }
                e = (Exception) e.getCause();
            }
            return null;
        }

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

        private void importCertificate(X509Certificate[] chain) throws CertificateException {
            FileOutputStream keyStoreFileOutputStream = null;
            boolean hasLock = false;
            final boolean debug = log.isDebugEnabled();
            final StopWatch watch = new StopWatch();
            try {
                for (X509Certificate cert : chain) {
                    String[] cnValues = AbstractVerifier.getCNs(cert);
                    String alias;

                    if (cnValues != null && cnValues.length > 0) {
                        alias = cnValues[0];
                    } else {
                        alias = "UnknownCN";
                    }

                    alias += "-ts=" + System.currentTimeMillis();

                    trustStore.setCertificateEntry(alias, cert);
                }
                KEYSTORE_WRITER_LOCK.lockInterruptibly();
                hasLock = true;
                keyStoreFileOutputStream = new FileOutputStream(keystoreConfig.getFilePath());
                trustStore.store(keyStoreFileOutputStream, keystoreConfig.getFilePassword().toCharArray());
            } catch (FileNotFoundException e) {
                // Can't find the keystore in the path
                log.error("Can't find the keystore in " + keystoreConfig.getFilePath() + ". Error message:"
                        + e.getMessage(), e);
            } catch (NoSuchAlgorithmException e) {
                log.error("The algorithm is not supported. Error message:" + e.getMessage(), e);
            } catch (Exception e) {
                // expect KeyStoreException, IOException
                log.error("Exception when trying to import certificate: " + e.getMessage(), e);
            } finally {
                close(keyStoreFileOutputStream);
                keyStoreFileOutputStream = null;
                if (hasLock) {
                    KEYSTORE_WRITER_LOCK.unlock();
                }
                if (debug)
                    log.debug("importCert: " + watch);
            }
        }

        private void close(FileOutputStream keyStoreFileOutputStream) {
            if (keyStoreFileOutputStream != null) {
                try {
                    keyStoreFileOutputStream.close();
                } catch (IOException e) {
                    log.error(e, e);
                }
            }
        }
    };
}

From source file:com.mytwitter.Network.NetworkHelper.java

/**
 * Create a trust manager that does not validate SSL certificate chains.
 *///from   w w  w  .j ava  2 s  .  co m
public void trustAllHosts() {

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

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

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

    // Install the all-trusting trust manager
    try {
        // Backup the current SSL socket factory
        defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.tc.util.io.ServerURL.java

private static void tweakSecureConnectionSettings(URLConnection urlConnection) {
    HttpsURLConnection sslUrlConnection;

    try {/*w w w . j  a v a2  s . c  om*/
        sslUrlConnection = (HttpsURLConnection) urlConnection;
    } catch (ClassCastException e) {
        throw new IllegalStateException("Unable to cast " + urlConnection
                + " to javax.net.ssl.HttpsURLConnection. "
                + "Options tc.ssl.trustAllCerts and tc.ssl.disableHostnameVerifier are causing this issue.", e);
    }

    if (DISABLE_HOSTNAME_VERIFIER) {
        // don't verify hostname
        sslUrlConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }

    TrustManager[] trustManagers = null;
    if (TRUST_ALL_CERTS) {
        // trust all certs
        trustManagers = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
                //
            }

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

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

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        sslUrlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Exception e) {
        throw new RuntimeException("unable to create SSL connection from " + urlConnection.getURL(), e);
    }
}

From source file:ui.shared.URLReader.java

private DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) throws Exception {
    final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
    try {/*from   w  w w . j a  v  a 2s .  c o  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public X509Certificate[] getAcceptedIssuers() {
                return _AcceptedIssuers;
            }

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

            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, httpClient.getParams());
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.vmware.bdd.plugin.ironfan.impl.RolePackageMapping.java

@SuppressWarnings("deprecation")
private String readDistroManifest() throws Exception {
    File manifestFile = new File(DISTRO_MANIFEST_FILE_PATH);
    if (manifestFile.exists()) {
        // The manifest file is on the local server.
        // No need to reload the file if it's not modified.
        if (lastModified != manifestFile.lastModified()) {
            lastModified = manifestFile.lastModified();
            logger.info("last modified date of manifest file changed. Reloading manifest.");
        } else {//from www. j  a  v a2  s  . c o m
            return null;
        }
    }

    BufferedReader in = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        SSLContext sslContext = SSLContexts.custom().useTLS().build();

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                return;
            }

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

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

        TlsClientConfiguration tlsConfiguration = new TlsClientConfiguration();
        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, tlsConfiguration.getSslProtocols(),
                tlsConfiguration.getCipherSuites(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpGet httpget = new HttpGet(new URI(distrosManifestUrl));
        if (eTag != null) {
            httpget.addHeader("If-None-Match", eTag);
        }

        logger.info("executing request: " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);

        if (!manifestFile.exists()) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
                return null;
            } else {
                logger.debug("ETag of manifest file changed. Reloading manifest.");
                eTag = response.getFirstHeader("ETag").getValue();
                ;
            }
        }
        HttpEntity entity = response.getEntity();

        in = new BufferedReader(new InputStreamReader(entity.getContent()));

        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        EntityUtils.consume(entity);
        return sb.toString();
    } finally {
        httpclient.getConnectionManager().shutdown();
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.vmware.photon.controller.deployer.deployengine.HttpFileServiceClient.java

private HttpsURLConnection createHttpConnection(URL destinationURL, String requestMethod) throws Exception {

    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*w  w  w  .ja  v a  2  s.  co m*/
        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;
        }
    } };

    final HostnameVerifier trustAllHostnames = (String hostname, SSLSession sslSession) -> true;

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

    String authType = "Basic "
            + new String(Base64.encodeBase64((this.userName + ":" + this.password).getBytes()));

    HttpsURLConnection httpConnection = (HttpsURLConnection) destinationURL.openConnection();
    httpConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    httpConnection.setHostnameVerifier(trustAllHostnames);
    httpConnection.setRequestMethod(requestMethod);
    httpConnection.setRequestProperty("Authorization", authType);
    return httpConnection;
}