Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:com.vmware.admiral.test.integration.BaseIntegrationSupportIT.java

protected static SSLSocketFactory getUnsecuredSSLSocketFactory()
        throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { UnsecuredX509TrustManager.getInstance() }, null);
    return context.getSocketFactory();
}

From source file:net.fenyo.mail4hotspot.service.MailManager.java

public static void trustSSL() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from   w  ww . j a v  a  2s .  co  m*/

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

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

    // c'est un pb de scurit, il faudrait mettre  jour les certifs racine et supprimer le all-trusting trust manager
    // 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) {
        System.out.println("Can not install the all-trusting trust manager");
    }
}

From source file:itdelatrisu.opsu.Utils.java

/**
 * Switches validation of SSL certificates on or off by installing a default
 * all-trusting {@link TrustManager}.//from w w w  . j av  a  2 s.  c o  m
 * @param enabled whether to validate SSL certificates
 * @author neu242 (http://stackoverflow.com/a/876785)
 */
public static void setSSLCertValidation(boolean enabled) {
    // create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

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

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

    // install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, enabled ? null : trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }
}

From source file:com.simiacryptus.util.Util.java

/**
 * Cache input stream./*from  ww w.j ava2 s .  c o m*/
 *
 * @param url  the url
 * @param file the file
 * @return the input stream
 * @throws IOException              the io exception
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws KeyStoreException        the key store exception
 * @throws KeyManagementException   the key management exception
 */
public static InputStream cache(String url, String file)
        throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    if (new File(file).exists()) {
        return new FileInputStream(file);
    } else {
        TrustManager[] trustManagers = { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, trustManagers, null);
        SSLSocketFactory sslFactory = ctx.getSocketFactory();
        URLConnection urlConnection = new URL(url).openConnection();
        if (urlConnection instanceof javax.net.ssl.HttpsURLConnection) {
            HttpsURLConnection conn = (HttpsURLConnection) urlConnection;
            conn.setSSLSocketFactory(sslFactory);
            conn.setRequestMethod("GET");
        }
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream cache = new FileOutputStream(file);
        return new TeeInputStream(inputStream, cache);
    }
}

From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java

public static void trustEverybody(HttpsURLConnection connection) {
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }/*  w w w  .java2  s  .c o  m*/
    };

    // Install the all-trusting trust manager and host name verifier
    SSLContext sc = getTrustEverybodySSLContext();

    if (connection == null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } else {
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(allHostsValid);
    }
}

From source file:info.guardianproject.netcipher.NetCipher.java

/**
 * Get a {@link TlsOnlySocketFactory} from NetCipher, and specify whether
 * it should use a more compatible, but less strong, suite of ciphers.
 *
 * @see HttpsURLConnection#setDefaultSSLSocketFactory(SSLSocketFactory)
 *//*from  www . jav a 2 s . c  om*/
public static TlsOnlySocketFactory getTlsOnlySocketFactory(boolean compatible) {
    SSLContext sslcontext;
    try {
        sslcontext = SSLContext.getInstance("TLSv1");
        sslcontext.init(null, null, null);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    } catch (KeyManagementException e) {
        throw new IllegalArgumentException(e);
    }
    return new TlsOnlySocketFactory(sslcontext.getSocketFactory(), compatible);
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Https/*from   w  w w .ja va2 s.c  om*/
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param trustManagers ??
 * @param outputJson    ?
 * @return 
 */
public static String doHttpsRequest(String requestUrl, String requestMethod, TrustManager[] trustManagers,
        String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        // SSLContext??
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(requestUrl);
        HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
        httpUrlConn.setSSLSocketFactory(ssf);
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("Weixin server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("https request error:", e);
    } finally {
        return result;
    }
}

From source file:eu.siacs.conversations.ui.ServiceBrowserFragment.java

public static boolean exists(String URLName) {

    X509TrustManager trustManager = new X509TrustManager() {

        @Override//from  ww w.ja va 2 s  . c  o  m
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

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

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

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    try {
        HttpsURLConnection.setFollowRedirects(false);
        // note : you may also need
        //        HttpURLConnection.setInstanceFollowRedirects(false)
        URL url = new URL(URLName);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setSSLSocketFactory(noSSLv3Factory);
        con.setRequestProperty("Accept-Encoding", "");
        //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        con.setHostnameVerifier(new NullHostNameVerifier(url.getHost()));
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpsURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * this method utoacepts all certificates in httpsurlconections
 * *//*from ww w  . ja  v  a2 s .c o  m*/
@SuppressLint("TrulyRandom")
private static void disableSSLCertificateChecking() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }
    } };
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:com.qingstor.sdk.request.QSOkHttpRequestClient.java

private static OkHttpClient getUnsafeOkHttpClient() {
    try {/*from ww w . j  ava 2s  .  c om*/
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };

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

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(QSConstant.HTTPCLIENT_CONNECTION_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(QSConstant.HTTPCLIENT_READ_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(QSConstant.HTTPCLIENT_WRITE_TIME_OUT, TimeUnit.SECONDS);
        builder.sslSocketFactory(sslSocketFactory);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage());
        throw new RuntimeException(e);
    }
}