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.signserver.client.cli.defaultimpl.KeyStoreOptions.java

private static void setDefaultSocketFactory(final KeyStore truststore, final KeyStore keystore, String keyAlias,
        char[] keystorePassword)
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(truststore);//from  w  w  w.j a  v  a2s  .c  o m

    final KeyManager[] keyManagers;
    if (keystore == null) {
        keyManagers = null;
    } else {
        if (keyAlias == null) {
            keyAlias = keystore.aliases().nextElement();
        }
        final KeyManagerFactory kKeyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        kKeyManagerFactory.init(keystore, keystorePassword);
        keyManagers = kKeyManagerFactory.getKeyManagers();
        for (int i = 0; i < keyManagers.length; i++) {
            if (keyManagers[i] instanceof X509KeyManager) {
                keyManagers[i] = new AliasKeyManager((X509KeyManager) keyManagers[i], keyAlias);
            }
        }
    }

    final SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagers, tmf.getTrustManagers(), new SecureRandom());

    SSLSocketFactory factory = context.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(factory);
}

From source file:org.neo4j.harness.InProcessBuilderTest.java

private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from   ww w .j  a v a 2 s  .c  om*/
        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;
        }
    } };

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

From source file:org.wso2.carbon.identity.sts.passive.ui.PassiveSTS.java

private void openURLWithNoTrust(String realm) throws IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//w  w  w  .  ja v  a2  s .  co m
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

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

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            // Nothing to implement
        }
    } };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        HostnameVerifier defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
        String renegotiation = System.getProperty("sun.security.ssl.allowUnsafeRenegotiation");
        try {
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
            new URL(realm).getContent();
        } finally {
            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
            HttpsURLConnection.setDefaultHostnameVerifier(defaultHostnameVerifier);
            System.getProperty("sun.security.ssl.allowUnsafeRenegotiation", renegotiation);
        }
    } catch (Exception ignore) {
        if (log.isDebugEnabled()) {
            log.debug("Error while installing trust manager", ignore);
        }
    }
}

From source file:org.craftercms.studio.impl.v1.service.cmis.CmisServiceImpl.java

private Session createCMISSession(DataSourceRepositoryTO config)
        throws CmisUnavailableException, CmisTimeoutException {

    if (config.isUseSsl()) {
        SSLContext sc = null;//from  w  w  w.jav  a 2 s  . c om
        try {
            sc = getSSLContext();
            // Ignore differences between given hostname and certificate hostname
            HostnameVerifier hv = (hostname, session) -> true;
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            logger.error("Error initializing SSL context", e);
        }
    }

    // Create a SessionFactory and set up the SessionParameter map
    SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
    Map<String, String> parameter = new HashMap<String, String>();
    parameter.put(SessionParameter.USER, config.getUsername());
    parameter.put(SessionParameter.PASSWORD, config.getPassword());

    // connection settings - we're connecting to a public cmis repo,
    // using the AtomPUB binding, but there are other options here,
    // or you can substitute your own URL
    parameter.put(SessionParameter.ATOMPUB_URL, config.getUrl());
    parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
    parameter.put(SessionParameter.COOKIES, "true");

    // find all the repositories at this URL - there should only be one.
    List<Repository> repositories = new ArrayList<Repository>();
    repositories = sessionFactory.getRepositories(parameter);

    // create session with the first (and only) repository
    Repository repository = repositories.get(0);
    parameter.put(SessionParameter.REPOSITORY_ID, repository.getId());
    Session session = null;
    try {
        session = sessionFactory.createSession(parameter);
    } catch (CmisConnectionException e) {
        throw new CmisTimeoutException(e);
    } catch (CmisBaseException e) {
        throw new CmisUnavailableException(e);
    }

    return session;
}

From source file:com.flipzu.flipzu.FlipInterface.java

/**
 * Trust every server - dont check for any certificate
 *///from   www  .  j  a  v a  2 s  .  c  o  m
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = 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 {
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(TAG, "trustAllHosts ERROR", e.getCause());
    }
}

From source file:de.pniehus.odal.App.java

/**
 * This method initializes a Trustmanager that accepts self signed ssl
 * certificates//  w  ww. j  a  v  a2s.co  m
 * 
 * This code of this method has been taken from
 * 
 * @see <a href="https://stackoverflow.com/a/4453908">this Stackoverflow
 *      post</a> and is licensed under the MIT License
 * 
 *      Copyright (c) 2010 nogudnik
 * 
 *      Permission is hereby granted, free of charge, to any person
 *      obtaining a copy of this software and associated documentation files
 *      (the "Software"), to deal in the Software without restriction,
 *      including without limitation the rights to use, copy, modify, merge,
 *      publish, distribute, sublicense, and/or sell copies of the Software,
 *      and to permit persons to whom the Software is furnished to do so,
 *      subject to the following conditions:
 * 
 *      The above copyright notice and this permission notice shall be
 *      included in all copies or substantial portions of the Software.
 * 
 *      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *      EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *      MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *      NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 *      BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 *      ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 *      CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *      SOFTWARE.
 * 
 */
public static void untrustedSSLSetup() {
    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) {
        mainLogger.severe("Unable to setup support for unverified SSL certificates: " + e.getMessage());
    }
}

From source file:com.nubits.nubot.utils.Utils.java

/**
 * Install a trust manager that does not validate certificate chains for https calls
 *
 * @throws Exception//w ww.  ja  v a  2 s  .c  om
 */
private static void installTrustAllManager() throws Exception {

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    // Install the all-trusting trust manager
    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() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@After
public void teardown() throws Exception {
    if (defaultSSLContext != null) {
        SSLContext.setDefault(defaultSSLContext);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }//from   ww  w .java2  s .c om

    if (restClient != null) {
        restClient.shutdown(timeout);
        restClient = null;
    }

    if (serverEndpoint != null) {
        serverEndpoint.closeAsync().get(timeout.getSize(), timeout.getUnit());
        serverEndpoint = null;
    }
}

From source file:ddf.common.test.cometd.CometDClient.java

private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//  w  w w  . jav a  2  s . c om
        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 null;
        }
    } };

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HostnameVerifier hostnameVerifier = (s, sslSession) -> s.equalsIgnoreCase(sslSession.getPeerHost());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
}

From source file:org.miloss.nexuscloner.Main.java

private static void initSsl() throws Exception {
    TrustManager[] trustall = new TrustManager[] { new X509TrustManager() {

        @Override/*  w  w w  . j  a  v  a 2 s. c om*/
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            System.out.println("Trust no one");
        }

        @Override
        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            System.out.println("Trust no one");
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            System.out.println("Trust no one");
            return null;
        }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");

    sc.init(null, trustall, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}