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:org.openmuc.framework.driver.rest.RestConnection.java

public RestConnection(String deviceAddress, String credentials, int timeout) throws ConnectionException {

    this.timeout = timeout;
    wrapper = new JsonWrapper();
    authString = new String(Base64.encodeBase64(credentials.getBytes()));

    if (!deviceAddress.endsWith("/")) {
        this.deviceAddress = deviceAddress + "/channels/";
    } else {//from ww  w  .j  a  v  a2  s. c  om
        this.deviceAddress = deviceAddress + "channels/";
    }

    if (deviceAddress.startsWith("https://")) {
        isHTTPS = true;
    } else {
        isHTTPS = false;
    }

    if (isHTTPS) {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            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 (KeyManagementException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        // HttpsURLConnection.setFollowRedirects(false);
    }
}

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

private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = { new X509TrustManager() {
        @Override//from   ww w  .  j  a v a 2  s.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:ddf.common.test.cometd.CometDClient.java

private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from  w  w w  .  j  ava  2 s  . c o  m
        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.aselect.authspserver.authsp.delegator.HTTPSTrustAllDelegate.java

public int authenticate(Map<String, String> requestparameters, Map<String, List<String>> responseparameters)
        throws DelegateException {
    String sMethod = "authenticate";
    int iReturnCode = -1;

    AuthSPSystemLogger _systemLogger;//w w  w.j  a  v  a  2 s  . c o m
    _systemLogger = AuthSPSystemLogger.getHandle();

    _systemLogger.log(Level.FINEST, sModule, sMethod,
            "requestparameters=" + requestparameters + " , responseparameters=" + responseparameters);
    StringBuffer data = new StringBuffer();
    String sResult = "";
    ;

    try {
        final String EQUAL_SIGN = "=";
        final String AMPERSAND = "&";
        final String NEWLINE = "\n";
        for (String key : requestparameters.keySet()) {
            data.append(URLEncoder.encode(key, "UTF-8"));
            data.append(EQUAL_SIGN).append(URLEncoder.encode(
                    ((String) requestparameters.get(key) == null) ? "" : (String) requestparameters.get(key),
                    "UTF-8"));
            data.append(AMPERSAND);
        }

        if (data.length() > 0)
            data.deleteCharAt(data.length() - 1); // remove last AMPERSAND
        //         data.append(NEWLINE).append(NEWLINE);
        //         _systemLogger.log(Level.FINE, sModule, sMethod, "url=" + url.toString() + " data={" + data.toString() + "}");   // no data shown in production environment

        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };
        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////

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

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////
        // Tell the url connection object to use our socket factory which bypasses security checks
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        /////////////   HERE WE DO THE TRUST ALL STUFF ///////////////////////////////

        // Basic authentication
        if (this.delegateuser != null) {
            byte[] bEncoded = Base64
                    .encodeBase64((this.delegateuser + ":" + (delegatepassword == null ? "" : delegatepassword))
                            .getBytes("UTF-8"));
            String encoded = new String(bEncoded, "UTF-8");
            conn.setRequestProperty("Authorization", "Basic " + encoded);
            _systemLogger.log(Level.FINEST, sModule, sMethod,
                    "Using basic authentication, user=" + this.delegateuser);
        }
        //         conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // They (the delegate party) don't accept charset !!
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data.toString());

        wr.flush();
        wr.close();

        // Get the response
        iReturnCode = conn.getResponseCode();
        Map<String, List<String>> hFields = conn.getHeaderFields();

        _systemLogger.log(Level.FINEST, sModule, sMethod, "response=" + iReturnCode);
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        // Still to decide on response protocol
        while ((line = rd.readLine()) != null) {
            sResult += line;
        }
        _systemLogger.log(Level.INFO, sModule, sMethod, "sResult=" + sResult);
        // Parse response  here
        // For test return request parameters
        //         responseparameters.putAll(requestparameters);
        responseparameters.putAll(hFields);

        rd.close();
    } catch (IOException e) {
        _systemLogger.log(Level.INFO, sModule, sMethod,
                "Error while reading sResult data, maybe no data at all. sResult=" + sResult);
    }

    catch (NumberFormatException e) {
        throw new DelegateException("Sending authenticate request, using \'" + this.url.toString()
                + "\' failed due to number format exception! " + e.getMessage(), e);
    } catch (Exception e) {
        throw new DelegateException("Sending authenticate request, using \'" + this.url.toString()
                + "\' failed (progress=" + iReturnCode + ")! " + e.getMessage(), e);
    }
    return iReturnCode;
}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password)
        throws GeneralSecurityException, IOException {

    KeyStore ks = this.getKeyStore(keyStoreName, password);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(ks, password.toCharArray());

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

    return context.getSocketFactory();
}

From source file:com.cyberway.issue.crawler.fetcher.HeritrixSSLProtocolSocketFactory.java

/**
 * Shutdown constructor./*  w w w .  j a v  a 2  s .com*/
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 */
public HeritrixSSLProtocolSocketFactory()
        throws KeyManagementException, KeyStoreException, NoSuchAlgorithmException {
    // Get an SSL context and initialize it.
    SSLContext context = SSLContext.getInstance("SSL");

    // I tried to get the default KeyManagers but doesn't work unless you
    // point at a physical keystore. Passing null seems to do the right
    // thing so we'll go w/ that.
    context.init(null,
            new TrustManager[] { new ConfigurableX509TrustManager(ConfigurableX509TrustManager.DEFAULT) },
            null);
    this.sslDefaultFactory = context.getSocketFactory();
}

From source file:com.redhat.lightblue.mongo.config.MongoConfiguration.java

private SocketFactory getSocketFactory() {
    try {/* w  w w .j  a  v a 2 s .co m*/
        if (noCertValidation) {
            LOGGER.warn("Certificate validation is off, don't use this in production");
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            return sc.getSocketFactory();
        } else {
            return SSLSocketFactory.getDefault();
        }
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.gdg.frisbee.android.api.OkStack.java

@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    SSLContext sslContext;
    try {//from   w  ww  .  j a  v a 2  s .c  o m
        TrustManager[] trustAllCerts = new TrustManager[] {
                new GdgTrustManager(App.getInstance().getApplicationContext()) };

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (GeneralSecurityException e) {
        throw new AssertionError(); // The system has no TLS. Just give up.
    }
    client.setSslSocketFactory(sslContext.getSocketFactory());
    return client.open(url);
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

/**
 * <pre>//from  ww  w .j av  a2  s  . c o  m
 *  ? ??   HTTPS   HandShake Exception ? ??  Exception? ? ?
 * RHEV Manager(host) ? SSL ??  ?   ? ?? ?.
 * </pre>
 * @throws Exception
 */
public void init() throws Exception {
    // http://javaresolutions.blogspot.kr/2014/07/javaxnetsslsslprotocolexception.html
    // -Djsse.enableSNIExtension=false
    // System.setProperty("jsse.enableSNIExtension", "false");

    System.setProperty("jsse.enableSNIExtension", "false");

    // Create a hostname verifier that does not validate hostname
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            /*
            if (hostname.equals(host)) {
            return true;
            }
                    
            return false;
            */
            return true;
        }
    });

    // Create a trust manager that does not validate certificate chains
    // Refer to https://code.google.com/p/misc-utils/wiki/JavaHttpsUrl
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // nothing to do.
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // nothing to do.
        }

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

    try {
        // Install the all-trusting trust manager
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (KeyManagementException e) {
        logger.error("KeyManagementException has occurred.", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException has occurred.", e);
    }
}