Example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDefaultSSLSocketFactory.

Prototype

public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the default SSLSocketFactory inherited by new instances of this class.

Usage

From source file:org.ojbc.web.portal.services.SamlServiceImpl.java

Element retrieveAssertionFromShibboleth(HttpServletRequest request) throws Exception {
    // Note: pulled this straight from Andrew's demo JSP that displays the assertion and http request...

    /*/*ww  w  . j av  a 2  s  .c  om*/
     *  fix for Exception in thread "main" javax.net.ssl.SSLHandshakeException:
     *       sun.security.validator.ValidatorException:
     *           PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
     *               unable to find valid certification path to requested target
     */
    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) {
        }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true; // andrew had this as false...dont know how that would work...
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    /*
     * end of the fix
     */
    //Hard coded to pick up a single assertion...could loop through assertion headers if there will  be more than one
    String assertionHttpHeaderName = request.getHeader("Shib-Assertion-01");
    LOG.info("Loading assertion from: " + assertionHttpHeaderName);

    if (assertionHttpHeaderName == null) {
        LOG.warn("Shib-Assertion-01 header was null, Returning null asssertion document element");
        return null;
    }

    URL url = new URL(assertionHttpHeaderName);
    URLConnection con = url.openConnection();

    InputStream is = con.getInputStream();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document assertionDoc = db.parse(is);

    return assertionDoc.getDocumentElement();

}

From source file:org.simple.net.httpstacks.HttpUrlConnStack.java

private void configHttps(Request<?> request) {
    if (request.isHttps()) {
        SSLSocketFactory sslFactory = mConfig.getSslSocketFactory();
        // ?https
        if (sslFactory != null) {
            HttpsURLConnection.setDefaultSSLSocketFactory(sslFactory);
            HttpsURLConnection.setDefaultHostnameVerifier(mConfig.getHostnameVerifier());
        }/*  w  w  w  .  ja va 2  s .  c  o m*/

    }
}

From source file:org.apache.fineract.restwebservice.PlatformRestClient.java

/**
 * Skip SSL certificate verification/* w  w w  . j ava2  s  . com*/
 */
private void skipSslCertificateVerification() {
    final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    try {
        // get the SSL context object
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // initialize the SSL context
        sslContext.init(null, trustManager, new SecureRandom());

        // Set the default SSLSocketFactory
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

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

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    } catch (Exception e) {
    }
}

From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java

private void configHttps(Request<?> request) {
    if (request.isHttps()) {
        SSLSocketFactory sslFactory = mConfig.getSslSocketFactory();
        // ?https
        if (sslFactory != null) {
            HttpsURLConnection.setDefaultSSLSocketFactory(sslFactory);
            HttpsURLConnection.setDefaultHostnameVerifier(mConfig.getHostnameVerifier());
        }/*  ww  w.  ja v a2  s . com*/
    }
}

From source file:org.apache.juddi.v3.client.cryptor.TransportSecurityHelper.java

public static boolean applyTransportSecurity(BindingProvider webServicePort) {
    try {//from w  w  w .j a v a 2s. com
        File currentdir = new File(".");
        String s = System.getProperty("javax.net.ssl.keyStore");
        String st = System.getProperty("javax.net.ssl.trustStore");
        log.info("Attempting to initialize keystore and truststore from " + s + " " + st);
        if (s == null) {
            log.warn("keystore isn't defined! " + s);
            return false;
        } else if (st == null) {
            log.warn("truststore isn't defined! " + s);
            return false;
        } else {
            File keystore = new File(s);
            if (keystore == null || !keystore.exists()) {
                log.warn("keystore doesn't exist! input was " + s + " working dir is "
                        + currentdir.getAbsolutePath());
                return false;
            }
            //File truststore =new File(System.getProperty("javax.net.ssl.trustStore"));
            String pwd = System.getProperty("javax.net.ssl.keyStorePassword");
            if (pwd == null) {
                log.warn("keystore password isn't defined!");
                return false;
            }

            File truststore = new File(st);
            if (truststore == null || !truststore.exists()) {
                log.warn("truststore doesn't exist! input was " + s + " working dir is "
                        + currentdir.getAbsolutePath());
                return false;
            }
            //File truststore =new File(System.getProperty("javax.net.ssl.trustStore"));
            String pwdt = System.getProperty("javax.net.ssl.trustStorePassword");
            if (pwdt == null) {
                log.warn("truststore password isn't defined!");
                return false;
            }

            if (keystore.exists()) {
                try {
                    log.info("Using keystore from " + keystore.getAbsolutePath() + " current dir is "
                            + currentdir.getAbsolutePath());

                    log.info("Using truststore from " + truststore.getAbsolutePath() + " current dir is "
                            + currentdir.getAbsolutePath());
                    //log.info("Using truststure from " + truststore.getAbsolutePath() + " current dir is " + currentdir.getAbsolutePath());
                    SSLContext sc = SSLContext.getInstance("SSLv3");

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

                    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                    ks.load(new FileInputStream(keystore), pwd.toCharArray());

                    kmf.init(ks, pwd.toCharArray());

                    String alg = TrustManagerFactory.getDefaultAlgorithm();
                    TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);

                    FileInputStream fis = new FileInputStream(st);
                    KeyStore kst = KeyStore.getInstance("jks");
                    kst.load(fis, pwdt.toCharArray());
                    fis.close();

                    tmFact.init(kst);

                    TrustManager[] tms = tmFact.getTrustManagers();

                    sc.init(kmf.getKeyManagers(), null, null);
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    ((BindingProvider) webServicePort).getRequestContext().put(
                            "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
                            sc.getSocketFactory());
                    ((BindingProvider) webServicePort).getRequestContext().put(
                            "com.sun.xml.ws.transport.https.client.SSLSocketFactory", sc.getSocketFactory());
                    return true;
                } catch (Exception ex) {
                    log.warn("unable to establish ssl settings", ex);
                }
            }
        }
        return false;
    } catch (Exception x) {
        log.error("unexpected error", x);
    }
    return false;
}

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

public static void configureEndpoint(String endpointPropertiesFile, String timeoutPropertyName,
        ServiceClient _serviceClient) {// w  w  w .j a  v  a2 s. c o  m
    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:io.hops.security.HopsUtil.java

/**
 * Set the default HTTPS trust policy to trust anything.
 *
 * NOTE: Use it only during development or use it wisely!
 *///from   w  w w.j  a v a 2  s  .co m
public static void trustAllHTTPS() {
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, trustAll, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (GeneralSecurityException ex) {
        throw new IllegalStateException("Could not initialize SSLContext for CRL fetcher", ex);
    }
}

From source file:riddimon.android.asianetautologin.HttpUtils.java

private HttpUtils(Context context) {
    // private constructor to prevent instantiation
    this.context = context;
    try {//from w  ww.j  ava2 s.co  m
        // get version number to be set as part of user agent string
        version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
    }
    if (debug) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        try {
            TrustManager[] trustManagers = new X509TrustManager[1];
            trustManagers[0] = new TrustAllManager();

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception ex) {
        }
    }
    // We don't enable response cache because this scenario requires fresh
    // data every time
    //enableHttpResponseCache();
}

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

/**
 * Makes HttpsURLConnection trusts a set of certificates specified by the KeyStore
 *//*  ww w.ja  v a  2  s  .  c  o m*/
public void fixHttpsURLConnection() {
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}

From source file:com.jwrapper.maven.java.JavaDownloadMojo.java

protected void setupNonVerifingSSL() throws Exception {

    // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from   www.jav  a 2  s . c  o m*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

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

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

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

}