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.jumpmind.symmetric.transport.TransportManagerFactory.java

public static void initHttps(final String httpSslVerifiedServerNames, boolean allowSelfSignedCerts) {
    try {//w  w w. j  a  v  a 2s  .com
        if (!StringUtils.isBlank(httpSslVerifiedServerNames)) {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslsession) {
                    boolean verified = false;
                    if (!StringUtils.isBlank(httpSslVerifiedServerNames)) {
                        if (httpSslVerifiedServerNames
                                .equalsIgnoreCase(Constants.TRANSPORT_HTTPS_VERIFIED_SERVERS_ALL)) {
                            verified = true;
                        } else {
                            String[] names = httpSslVerifiedServerNames.split(",");
                            for (String string : names) {
                                if (s != null && s.equals(string.trim())) {
                                    verified = true;
                                    break;
                                }
                            }
                        }
                    }
                    return verified;
                }
            });
        }

        if (allowSelfSignedCerts) {
            HttpsURLConnection.setDefaultSSLSocketFactory(createSelfSignedSocketFactory());
        }

    } catch (GeneralSecurityException ex) {
        throw new SecurityException(ex);
    }

}

From source file:com.grantedbyme.example.ServletUtils.java

public static GrantedByMe getSDK(HttpServlet context) throws IOException {
    // read private key
    String privateKey = null;/* www  . ja  v  a  2  s.  c o m*/
    InputStream privateKeyInputStream = context.getClass().getResourceAsStream("/private_key.pem");
    try {
        privateKey = IOUtils.toString(privateKeyInputStream);
    } finally {
        privateKeyInputStream.close();
    }
    // read server key
    String serverKey = null;
    InputStream serverKeyInputStream = context.getClass().getResourceAsStream("/server_key.pem");
    try {
        serverKey = IOUtils.toString(serverKeyInputStream);
    } finally {
        serverKeyInputStream.close();
    }
    // _log(serverKey);
    // initialize BouncyCastle security provider
    Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 0);
    // create sdk
    GrantedByMe sdk = new GrantedByMe(privateKey, serverKey);
    // 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(java.security.cert.X509Certificate[] certs, String authType) {
            //No need to implement.
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            //No need to implement.
        }
    } };
    // 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) {
        e.printStackTrace();
    }
    // set SDK parameters
    sdk.apiURL = "https://api-dev.grantedby.me/v1/service/";
    //sdk.isDebug = true;
    return sdk;
}

From source file:org.ksoap2.transport.ServiceConnectionSE.java

public ServiceConnectionSE(String url) throws IOException {
    // /*from  w ww  .  ja  v  a2  s .c o m*/
    try {
        SSLContext sContext = SSLContext.getInstance("SSL");
        sContext.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sContext.getSocketFactory());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    connection = (HttpsURLConnection) new URL(url).openConnection();
    ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setDoInput(true);
}

From source file:to.sparks.mtgox.net.HTTPAuthenticator.java

public HTTPAuthenticator(final Logger logger, String apiKey, String secret) {
    this.apiKey = apiKey;
    this.secret = secret;

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override//from  ww  w .  j a  v a  2  s .  c  o m
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        @Override
        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) {

        logger.log(Level.SEVERE, null, e);
    }

}

From source file:com.groupon.odo.tests.HttpUtils.java

public static String doProxyHttpsGet(String url, BasicNameValuePair[] data) throws Exception {
    String fullUrl = url;//from   w  w  w  .  ja v a 2 s  .  c o m

    if (data != null) {
        if (data.length > 0) {
            fullUrl += "?";
        }

        for (BasicNameValuePair bnvp : data) {
            fullUrl += bnvp.getName() + "=" + uriEncode(bnvp.getValue()) + "&";
        }
    }

    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) {
    }

    URL uri = new URL(fullUrl);
    int port = Utils.getSystemPort(Constants.SYS_FWD_PORT);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", port));
    URLConnection connection = uri.openConnection(proxy);

    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String accumulator = "";
    String line = "";
    Boolean firstLine = true;
    while ((line = rd.readLine()) != null) {
        accumulator += line;
        if (!firstLine) {
            accumulator += "\n";
        } else {
            firstLine = false;
        }
    }

    return accumulator;
}

From source file:net.sf.jsignpdf.ssl.SSLInitializer.java

public static final void init() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
        CertificateException, IOException {
    if (Constants.RELAX_SSL_SECURITY) {
        LOGGER.debug("Relaxing SSL security.");

        //Details for the properties - http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html
        //Workaround for http://sourceforge.net/tracker/?func=detail&atid=1037906&aid=3491269&group_id=216921
        System.setProperty("jsse.enableSNIExtension", "false");

        //just in case...
        System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
        System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true");

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }/*  ww  w .j  a va2s . c om*/
        });
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, TRUST_MANAGERS, null);

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}

From source file:net.sileht.lullaby.Utils.java

public static void setSSLCheck(Boolean insecure) {
    if (insecure) {
        HttpsURLConnection.setDefaultSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(-1, null));
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {/*from   ww w  .  j a  va 2  s  .co  m*/
        HttpsURLConnection.setDefaultSSLSocketFactory(SSLCertificateSocketFactory.getDefault(-1, null));
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }
}

From source file:com.cloupia.feature.nimble.http.MySSLSocketFactory.java

public Socket createSocket(Socket socket, String host, int port, boolean flag)
        throws IOException, UnknownHostException {

    TrustManager[] trustAllCerts = getTrustManager();

    try {// w w w .j  ava2  s  .  c o  m

        SSLContext sc = SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        SocketFactory socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        return socketFactory.createSocket(host, port);

    }

    catch (Exception ex) {

        throw new UnknownHostException("Problems to connect " + host + ex.toString());

    }

}

From source file:com.zimbra.common.net.SocketFactories.java

private synchronized static void register(X509TrustManager tm) {
    if (registered)
        return;/*  w ww .ja va 2  s  . c o m*/

    // Set default TrustManager
    TrustManagers.setDefaultTrustManager(tm);

    // Register Apache Commons HTTP/HTTPS protocol socket factories
    ProtocolSocketFactory psf = defaultProtocolSocketFactory();
    Protocol.registerProtocol(HTTP, new Protocol(HTTP, psf, 80));
    ProtocolSocketFactory spsf = defaultSecureProtocolSocketFactory();
    Protocol.registerProtocol(HTTPS, new Protocol(HTTPS, spsf, 443));

    // HttpURLConnection already uses system ProxySelector by default
    // Set HttpsURLConnection SSL socket factory and optional hostname verifier
    HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory(false));
    if (tm instanceof CustomTrustManager) {
        HttpsURLConnection.setDefaultHostnameVerifier(new CustomHostnameVerifier());
    }

    // Set the system-wide default ProxySelector
    ProxySelector.setDefault(ProxySelectors.defaultProxySelector());

    registered = true;
}

From source file:org.hyperic.hq.plugin.appha.VSphereUtil.java

private static void configureSSLKeystore() {
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig,
            keystoreConfig.isAcceptUnverifiedCert());
    SSLContext sslContext = sslProvider.getSSLContext();
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new AllowAllHostnameVerifier());
}