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:be.fedict.eid.idp.sp.protocol.openid.OpenIDSSLSocketFactory.java

/**
 * Install the OpenID SSL Socket Factory. Trusts the given server
 * certificate and all default trusted server certificates.
 * //from  w  w w  .  j ava2s .  c om
 * @param serverCertificate
 *            SSL Certificate to trust
 * @throws NoSuchAlgorithmException
 *             could not get an SSLContext instance
 * @throws KeyManagementException
 *             failed to initialize the SSLContext
 * @throws KeyStoreException
 *             failed to intialize the {@link OpenIDTrustManager}
 */
public static void install(X509Certificate serverCertificate)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLSocketFactory sslSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    if (!(sslSocketFactory instanceof OpenIDSSLSocketFactory)) {
        LOG.debug("installing OpenID SSL Socket Factory...");
        OpenIDSSLSocketFactory openIDSSLSocketFactory = new OpenIDSSLSocketFactory(serverCertificate);
        HttpsURLConnection.setDefaultSSLSocketFactory(openIDSSLSocketFactory);
    } else {
        LOG.debug("OpenID SSL Socket Factory already installed.");
    }
}

From source file:org.sickbeard.SickBeard.java

public SickBeard(String hostname, String port, String api, boolean https, String extraPath, String user,
        String password, boolean trustAll, String trustMe) {
    this.hostname = hostname;
    this.port = port;
    this.extraPath = "/" + extraPath + "/";
    this.path = this.extraPath + "/api/" + api + "/";
    try {//from   ww w.ja va  2 s  . c  o m
        this.https = https;
        this.scheme = https ? "https" : "http";

        Authenticator.setDefault(new SickAuthenticator(user, password, hostname));
        HostnameVerifier verifier;
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (Exception e) {
        ;
    }
    /***********************************************************
     * ANDROID SPECIFIC START                                  *
     ***********************************************************/
    // start a AsyncTask to try and find the actual api version number
    AsyncTask<Void, Void, CommandsJson> task = new AsyncTask<Void, Void, CommandsJson>() {
        @Override
        protected CommandsJson doInBackground(Void... arg0) {
            try {
                return SickBeard.this.sbGetCommands();
            } catch (Exception e) {
                Log.e("SickBeard", e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(CommandsJson result) {
            // do nothing because this is a network error
            if (result == null)
                return;
            try {
                // if we get a version use it
                SickBeard.this.apiVersion = Integer.valueOf(result.api_version);
            } catch (NumberFormatException e) {
                // 2 was the odd float so assume its 2 if we cant get an int
                SickBeard.this.apiVersion = 2;
            }
        }
    };
    task.execute();
    /***********************************************************
     * ANDROID SPECIFIC END                                    *
     ***********************************************************/
}

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

private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = { new X509TrustManager() {
        @Override/*from   w ww.ja v a2s.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:it.haefelinger.flaka.util.InitSSL.java

static public void install(TrustManager tm) throws Exception {
    // There's a problem (bug?) in Java 1.4 causing sc.init() to take a
    // very long time. Disabling installation of new trustmanager if
    // not 1.5 or newer. That's just fine cause 1.4 trustmanger accepts
    // self signed certificates.
    if (isjava15()) {
        SSLContext sc;/*  w  w  w. ja  v a  2s .  c o m*/
        sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { tm }, null);
        /* register with standard HTTP implementation */
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        /* register with Jakarta HTTPClient */
        Protocol https = new Protocol("https", new SSLSocketFactory(sc), 443);
        Protocol.registerProtocol("https", https);
    }
}

From source file:tk.egsf.ddns.JSON_helper.java

public static String postToUrl(String URL, String Auth, JSONObject post) {
    String ret = "";

    String https_url = URL;
    URL url;//w w w .jav a2  s  .  c o  m
    try {

        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            @Override
            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());

        url = new URL(https_url);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        con.setRequestProperty("Authorization", Auth);
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.connect();

        //          Send post
        System.out.println(post.toString());

        byte[] outputBytes = post.toString().getBytes("UTF-8");
        OutputStream os = con.getOutputStream();
        os.write(outputBytes);
        os.close();

        //            get response
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String input;
        while ((input = br.readLine()) != null) {
            ret += input;
        }
        br.close();

        System.out.println(ret);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        //            e.printStackTrace();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
    }

    return ret;
}

From source file:ezbake.deployer.publishers.SecurityServiceClient.java

protected HttpsURLConnection openUrlConnection(URL endpoint) throws IOException, SSLContextException {

    SSLContext sslContext = EzSSL.getSSLContext(config.getEzConfiguration());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override//from  w w  w  .ja  v a 2 s  .  c  o  m
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    return (HttpsURLConnection) endpoint.openConnection();
}

From source file:org.robam.xutils.Utils.OtherUtils.java

/**
 *
 *///  ww w . j ava 2s  .c  o m
public static void trustAllSSLForHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (trustAllCerts == null) {
        trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
    }
    // Install the all-trusting trust manager
    final SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Throwable e) {
        LogUtils.e(e.getMessage(), e);
    }
    HttpsURLConnection
            .setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

private static void setupSslProps(Configuration conf) throws IOException {
    FileInputStream fis = null;//w  w w .j  a v a 2 s.  c o m
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        KeyManager[] kms = null;
        TrustManager[] tms = null;
        if (conf.get("ssl.client.keystore.location") != null) {
            // initialize default key manager with keystore file and pass
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            KeyStore ks = KeyStore.getInstance(conf.get("ssl.client.keystore.type", "JKS"));
            char[] ksPass = conf.get("ssl.client.keystore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.keystore.location", "keystore.jks"));
            ks.load(fis, ksPass);
            kmf.init(ks, conf.get("ssl.client.keystore.keypassword", "changeit").toCharArray());
            kms = kmf.getKeyManagers();
            fis.close();
            fis = null;
        }
        // initialize default trust manager with keystore file and pass
        if (conf.getBoolean("ssl.client.do.not.authenticate.server", false)) {
            // by pass trustmanager validation
            tms = new DummyTrustManager[] { new DummyTrustManager() };
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
            KeyStore ts = KeyStore.getInstance(conf.get("ssl.client.truststore.type", "JKS"));
            char[] tsPass = conf.get("ssl.client.truststore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.truststore.location", "truststore.jks"));
            ts.load(fis, tsPass);
            tmf.init(ts);
            tms = tmf.getTrustManagers();
        }
        sc.init(kms, tms, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        throw new IOException("Could not initialize SSLContext", e);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}

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 w ww .  ja  v 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:wsattacker.plugin.intelligentdos.requestSender.Http4RequestSenderImpl.java

private SSLSocketFactory get() {

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

    // Install the all-trusting trust manager
    try {/*from www  .  j ava 2 s. c  om*/
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        return new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (RuntimeException e) {
        ;
    } catch (Exception e) {
        ;
    }

    return null;

}