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.openo.sdnhub.overlayvpndriver.http.OverlayVpnDriverSsoProxy.java

private OverlayVpnDriverSsoProxy(final String acIp, final String acPort, final String acLoginName,
        String acLoginPassword) {
    this.acIp = acIp;
    this.acPort = acPort;
    this.acLoginName = acLoginName;
    this.acLoginPassword = acLoginPassword;
    try {/*from www .  j a  v  a 2 s. c o  m*/
        SSLContext sslcontext = SSLContext.getInstance(SSLCONTEST_TLS);
        sslcontext.init(null, new TrustManager[] { new X509TrustManager() {

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

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

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

        X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();
        HttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

        httpClient = HttpClients.custom().setConnectionManager(connManager)
                .setRedirectStrategy(new LaxRedirectStrategy()).build();
    } catch (Exception e) {
        LOGGER.error("ACSSOProxy: throw exception.", e);
    }
}

From source file:org.aselect.authspserver.authsp.delegator.HTTPSTrustAllDelegate.java

public int authenticate(Map<String, String> requestparameters, Map<String, List<String>> responseparameters)
        throws DelegateException {
    String sMethod = "authenticate";
    int iReturnCode = -1;

    AuthSPSystemLogger _systemLogger;/*ww  w  .j a  va  2s  .c om*/
    _systemLogger = AuthSPSystemLogger.getHandle();

    _systemLogger.log(Level.FINEST, sModule, sMethod,
            "requestparameters=" + requestparameters + " , responseparameters=" + responseparameters);
    StringBuffer data = new StringBuffer();
    String sResult = "";
    ;

    try {
        final String EQUAL_SIGN = "=";
        final String AMPERSAND = "&";
        final String NEWLINE = "\n";
        for (String key : requestparameters.keySet()) {
            data.append(URLEncoder.encode(key, "UTF-8"));
            data.append(EQUAL_SIGN).append(URLEncoder.encode(
                    ((String) requestparameters.get(key) == null) ? "" : (String) requestparameters.get(key),
                    "UTF-8"));
            data.append(AMPERSAND);
        }

        if (data.length() > 0)
            data.deleteCharAt(data.length() - 1); // remove last AMPERSAND
        //         data.append(NEWLINE).append(NEWLINE);
        //         _systemLogger.log(Level.FINE, sModule, sMethod, "url=" + url.toString() + " data={" + data.toString() + "}");   // no data shown in production environment

        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

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

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////
        // Tell the url connection object to use our socket factory which bypasses security checks
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////

        // Basic authentication
        if (this.delegateuser != null) {
            byte[] bEncoded = Base64
                    .encodeBase64((this.delegateuser + ":" + (delegatepassword == null ? "" : delegatepassword))
                            .getBytes("UTF-8"));
            String encoded = new String(bEncoded, "UTF-8");
            conn.setRequestProperty("Authorization", "Basic " + encoded);
            _systemLogger.log(Level.FINEST, sModule, sMethod,
                    "Using basic authentication, user=" + this.delegateuser);
        }
        //         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // They (the delegate party) don't accept charset !!
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data.toString());

        wr.flush();
        wr.close();

        // Get the response
        iReturnCode = conn.getResponseCode();
        Map<String, List<String>> hFields = conn.getHeaderFields();

        _systemLogger.log(Level.FINEST, sModule, sMethod, "response=" + iReturnCode);
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        // Still to decide on response protocol
        while ((line = rd.readLine()) != null) {
            sResult += line;
        }
        _systemLogger.log(Level.INFO, sModule, sMethod, "sResult=" + sResult);
        // Parse response  here
        // For test return request parameters
        //         responseparameters.putAll(requestparameters);
        responseparameters.putAll(hFields);

        rd.close();
    } catch (IOException e) {
        _systemLogger.log(Level.INFO, sModule, sMethod,
                "Error while reading sResult data, maybe no data at all. sResult=" + sResult);
    }

    catch (NumberFormatException e) {
        throw new DelegateException("Sending authenticate request, using \'" + this.url.toString()
                + "\' failed due to number format exception! " + e.getMessage(), e);
    } catch (Exception e) {
        throw new DelegateException("Sending authenticate request, using \'" + this.url.toString()
                + "\' failed (progress=" + iReturnCode + ")! " + e.getMessage(), e);
    }
    return iReturnCode;
}

From source file:org.obiba.mica.core.service.AgateRestService.java

/**
 * Do not check anything from the remote host (Agate server is trusted).
 *
 * @return/*from ww  w. ja va  2 s. c om*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private SSLConnectionSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    // Accepts any SSL certificate
    TrustManager tm = 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;
        }
    };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { tm }, null);

    return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

From source file:org.parosproxy.paros.core.proxy.WithBasicInfrastructureIntegrationTest.java

/**
 * Use custom TrustManager that trusts everything.
 * Moreover setup custom ProtocolSocketFactory as done in ZAP.
 * /*from w  w w. j a  v  a2 s  . com*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
protected static void initializeLocalSecurity() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // everything is trusted
        }

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

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

    // this doesn't seem to apply to connections through a proxy
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    // setup a hostname verifier that verifies everything
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new SSLConnector(), 443));
}

From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java

private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = { new X509TrustManager() {
        @Override/* ww  w. j  a  va2s  . c  o  m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
            //
        }
    } };
    final SSLContext sc = SSLContext.getInstance("SSL");
    final HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    };
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:org.socialbiz.cog.util.SSLPatch.java

/**
* Java proides a standard "trust manager" interface.  This trust manager
* essentially disables the rejection of certificates by trusting anyone and everyone.
*/// w  ww .  j  a  v  a 2  s .  c  o m
public static X509TrustManager getDummyTrustManager() {
    return new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

From source file:edu.indiana.d2i.htrc.dataapi.DataAPIWrapper.java

private void initSSL(boolean isSelfSigned) throws NoSuchAlgorithmException, KeyManagementException {
    if (isSelfSigned) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }//from www.j  av a 2  s  . com

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

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

            @SuppressWarnings("unused")
            public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
                return true;
            }

            @SuppressWarnings("unused")
            public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
                return true;
            }
        } };

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

From source file:co.cask.cdap.gateway.router.NettyRouterHttpsTest.java

@Override
protected SocketFactory getSocketFactory() throws Exception {
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, new TrustManager[] { new X509TrustManager() {
        @Override/*from  ww  w .  j av 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 new X509Certificate[0];
        }
    } }, new java.security.SecureRandom());
    return sc.getSocketFactory();
}

From source file:org.dataconservancy.archive.impl.fcrepo.ri.MultiThreadedHttpClient.java

private static SSLSocketFactory createSSLSocketFactory(boolean skipSSLTrustCheck,
        boolean skipSSLHostnameVerification) {
    SSLContext sslContext = null;
    try {/*from   w ww . j  a v a 2 s  .  c o m*/
        if (skipSSLTrustCheck) {
            sslContext = SSLContext.getInstance("TLS");
            TrustManager easyTrustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // Oh, I am easy!
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        } else {
            sslContext = SSLContext.getDefault();
        }
    } catch (KeyManagementException wontHappen) {
        throw new RuntimeException(wontHappen);
    } catch (NoSuchAlgorithmException wontHappen) {
        throw new RuntimeException(wontHappen);
    }
    SSLSocketFactory factory = new SSLSocketFactory(sslContext);
    if (skipSSLHostnameVerification) {
        factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    return factory;
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.http.HttpClientFactory.java

/**
 * Gets a SchemeRegistry object accepting all the X509 certificates by default.
 * @return A SchemeRegistry object./*from  w  w  w .java  2s  .c  om*/
 */
private SchemeRegistry getSchemeRegistry() {
    // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0

    SSLContext sslContext = null;

    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        logger.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

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

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

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } // checkServerTrusted
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    if (sslContext == null) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)");
        return null;
    } // if

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