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:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * SSL?TrustManager???SSL?//from ww w .j  a  v  a 2  s . c om
 * HttpsURLConnection????
 */
private void trustAllHosts() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }

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

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

    // all-trusting TrustManager
    try {
        // ?SSL
        mDefaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // TrustManager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        XLog.e(CLASS_NAME, e.getMessage());
    }
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Helper method to setup STS Client.//from   w  w  w.j a v a  2  s .com
 */
private void configureStsClient() {
    LOGGER.debug("Configuring the STS client.");

    try {
        HttpsURLConnection.setDefaultSSLSocketFactory(CommonSSLFactory.createSocket(trustStorePath,
                trustStorePassword, keyStorePath, keyStorePassword));
    } catch (IOException ioe) {
        throw new RuntimeException("Could not create SSL connection with given trust/key stores.", ioe);
    }

    configureBaseStsClient();

    addStsProperties();

    setClaimsOnStsClient(createClaimsElement());

    if (stsClient.getWsdlLocation() != null && stsClient.getWsdlLocation().startsWith(HTTPS)) {
        setupSslOnStsClientHttpConduit();
    } else {
        LOGGER.debug("STS address is null, unable to create STS Client");
    }

    if (LOGGER.isDebugEnabled()) {
        logStsClientConfiguration();
    }
}

From source file:org.wso2.carbon.apimgt.core.impl.AMDefaultKeyManagerImpl.java

private static void createSSLConnection()
        throws NoSuchAlgorithmException, java.security.KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }//from w  w  w .j  a  v  a2  s  .com

        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());
}

From source file:com.trsst.Common.java

/**
 * Most trsst nodes run with self-signed certificates, so by default we
 * accept them. While posts are still signed and/or encrypted, a MITM can
 * still refuse our out-going posts and suppress incoming new ones, but this
 * the reason to relay with many trsst servers. Use the -strict option to
 * require CA-signed certificates. Note that nowadays CA-signed certs are no
 * guarantee either./*from   w  ww .j a  v  a2  s .co  m*/
 */
public static void enableAnonymousSSL() {
    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) {
        }

    } };

    SSLContext sc;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
        log.error("Can't get SSL context", e);
    } catch (KeyManagementException e) {
        log.error("Can't set SSL socket factory", e);
    }

    // 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);

    // For apache http client
    Protocol anonhttps = new Protocol("https", (ProtocolSocketFactory) new AnonymSSLSocketFactory(), 443); //
    Protocol.registerProtocol("https", anonhttps);
}

From source file:com.example.android.networkconnect.MainActivity.java

private static void trustAllHosts() {

    X509TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy!
        }/*from  w w w .  j a v a  2 s . c  o m*/

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

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

    };

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager };

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

From source file:com.cloudera.beeswax.BeeswaxServiceImpl.java

/**
 * Create a new BeeswaxServiceImpl./*from  www.jav  a2s  .  c o  m*/
 *
 * @param dtHost The Hue host (ip or hostname).
 * @param dtPort The port Desktop runs on.
 * @param dtHttps Whether Desktop is running https.
 * @param queryLifetime The life time of a cached query.
 */
public BeeswaxServiceImpl(String dtHost, int dtPort, boolean dtHttps, long queryLifetime) {
    LogContext.initLogCapture();
    this.executor = Executors.newCachedThreadPool(new NamingThreadFactory("Beeswax-%d"));
    this.runningQueries = new ConcurrentHashMap<String, RunningQueryState>();
    this.queryLifetime = queryLifetime;

    if (dtPort == -1) {
        this.notifyUrl = null;
    } else {
        String protocol;
        if (dtHttps) {
            try {
                // Disable SSL verification. HUE cert may be signed by untrusted CA.
                SSLContext sslcontext = SSLContext.getInstance("SSL");
                sslcontext.init(null, new DummyX509TrustManager[] { new DummyX509TrustManager() },
                        new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
            } catch (NoSuchAlgorithmException ex) {
                LOG.warn("Failed to disable SSL certificate check " + ex);
            } catch (KeyManagementException ex) {
                LOG.warn("Failed to disable SSL certificate check " + ex);
            }
            DummyHostnameVerifier dummy = new DummyHostnameVerifier();
            HttpsURLConnection.setDefaultHostnameVerifier(dummy);
            protocol = "https";
        } else {
            protocol = "http";
        }
        this.notifyUrl = protocol + "://" + dtHost + ":" + dtPort + NOTIFY_URL_BASE;
    }

    // A daemon thread that periodically evict stale RunningQueryState objects
    Thread evicter = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                long now = System.currentTimeMillis();
                for (Map.Entry<String, RunningQueryState> entry : runningQueries.entrySet()) {
                    RunningQueryState rqState = entry.getValue();
                    //safe guard against small value of lifetime, only clean FINISHED or EXCEPTION state
                    if ((rqState.state == QueryState.FINISHED || rqState.state == QueryState.EXCEPTION)
                            && rqState.getAtime() + getQueryLifetime() < now) {
                        String id = entry.getKey();
                        runningQueries.remove(id);
                        LOG.debug("Removed " + rqState.toString());
                        Thread.yield(); // be nice
                    }
                }

                LogContext.garbageCollect(getQueryLifetime());

                long wakeup = now + EVICTION_INTERVAL;
                while (System.currentTimeMillis() < wakeup) {
                    try {
                        Thread.sleep(EVICTION_INTERVAL);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }
    }, "Evicter");
    evicter.setDaemon(true);
    evicter.start();
}

From source file:org.kawanfw.commons.client.http.HttpTransferOne.java

/**
 * If called, self signed SSL certificates will be accepted
 *///w  w w.  jav  a  2s.  c  om
private void acceptSelfSignedSslCert() {
    // 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 = null;
    try {
        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);

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

}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

public void testThatBasicAuthIsSupportedWithHttps() throws Exception {
    assumeTrue("test requires security manager to be disabled", System.getSecurityManager() == null);

    SSLSocketFactory defaultSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    ServerBootstrap serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory());
    SelfSignedCertificate ssc = new SelfSignedCertificate("localhost");

    try {/*from   w  w w  .  j a  v  a  2  s.  co  m*/

        //  Create a trust manager that does not validate certificate chains:
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        final List<HttpRequest> requests = new ArrayList<>();
        final SslContext sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());

        serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new SslHandler(sslContext.newEngine()), new HttpRequestDecoder(),
                        new HttpResponseEncoder(), new LoggingServerHandler(requests));
            }
        });

        Channel channel = serverBootstrap.bind(new InetSocketAddress(InetAddress.getByName("localhost"), 0));
        int port = ((InetSocketAddress) channel.getLocalAddress()).getPort();
        // IO_ERROR because there is no real file delivered...
        assertStatus(
                String.format(Locale.ROOT,
                        "install https://user:pass@localhost:%s/foo.zip --verbose --timeout 1s", port),
                ExitStatus.IO_ERROR);

        // ensure that we did not try any other data source like download.elastic.co, in case we specified our own local URL
        assertThat(terminal.getTerminalOutput(), not(hasItem(containsString("download.elastic.co"))));

        assertThat(requests, hasSize(1));
        String msg = String.format(Locale.ROOT,
                "Request header did not contain Authorization header, terminal output was: %s",
                terminal.getTerminalOutput());
        assertThat(msg, requests.get(0).headers().contains("Authorization"), is(true));
        assertThat(msg, requests.get(0).headers().get("Authorization"),
                is("Basic " + Base64.encodeBytes("user:pass".getBytes(StandardCharsets.UTF_8))));
    } finally {
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSocketFactory);
        serverBootstrap.releaseExternalResources();
        ssc.delete();
    }
}

From source file:com.dynatrace.license.count.monitor.counter.java

public void disableCertificateValidation() {
    log.finer("Entering disableCertificateValidation method");
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }/*from  w w  w . j  ava  2  s .co m*/

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

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

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
        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());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {
    }

    log.finer("Exiting disableCertificateValidation method");
}

From source file:org.codice.alliance.nsili.client.NsiliClient.java

private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from 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;
        }
    } };

    // Set HttpsURLConnection settings
    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);
}