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.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private SSLSocketFactory generateSSLContextWhichAcceptAllSSLCertificats() {
    Security.addProvider(Security.getProvider("SunJCE"));
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override//  w  w w  .  j a  v  a 2 s  .c  o m
        public java.security.cert.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 sslContext = SSLContext.getInstance("SSL");

        sslContext.init(null, trustAllCerts, new SecureRandom());

        return sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        logger.error("A KeyManagementException occurred", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("A NoSuchAlgorithmException occurred", e);
    }
    return null;
}

From source file:org.gluu.oxtrust.ldap.service.StatusCheckerTimer.java

private String getHttpdPage(String idpUrl, String httpdTestPageName) {
    String[] urlParts = idpUrl.split("://");
    if ("https".equals(urlParts[0])) {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }//w  w  w .jav  a  2  s.c om

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

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

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

    StringBuilder sb = new StringBuilder();
    // Now you can access an https URL without having the certificate in the
    // truststore
    try {
        String[] hostAndPort = urlParts[1].split(":");
        URL url = null;
        if (hostAndPort.length < 2) {
            url = new URL(urlParts[0], hostAndPort[0], httpdTestPageName);
        } else {
            url = new URL(urlParts[0], hostAndPort[0], Integer.parseInt(hostAndPort[1]), httpdTestPageName);
        }
        InputStream in = url.openConnection().getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        in.close();

    } catch (Exception e) {
        // log.error("Failed to get test page: ", e);
    }
    return sb.toString();
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public String getMediaIds(File[] pics, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    String ids = "";

    for (int i = 0; i < pics.length; i++) {
        File file = pics[i];/*from w  w w .  j a va  2 s .co  m*/
        try {
            AccessToken token = twitter.getOAuthAccessToken();
            String oauth_token = token.getToken();
            String oauth_token_secret = token.getTokenSecret();

            // generate authorization header
            String get_or_post = "POST";
            String oauth_signature_method = "HMAC-SHA1";

            String uuid_string = UUID.randomUUID().toString();
            uuid_string = uuid_string.replaceAll("-", "");
            String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

            // get the timestamp
            Calendar tempcal = Calendar.getInstance();
            long ts = tempcal.getTimeInMillis();// get current time in milliseconds
            String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

            // the parameter string must be in alphabetical order, "text" parameter added at end
            String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                    + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                    + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
            System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

            String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json";
            String twitter_endpoint_host = "upload.twitter.com";
            String twitter_endpoint_path = "/1.1/media/upload.json";
            String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                    + encode(parameter_string);
            String oauth_signature = computeSignature(signature_base_string,
                    AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

            String authorization_header_string = "OAuth oauth_consumer_key=\""
                    + AppSettings.TWITTER_CONSUMER_KEY
                    + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                    + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
            HttpProtocolParams.setUseExpectContinue(params, false);
            HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                    // Required protocol interceptors
                    new RequestContent(), new RequestTargetHost(),
                    // Recommended protocol interceptors
                    new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
            HttpContext context = new BasicHttpContext(null);
            HttpHost host = new HttpHost(twitter_endpoint_host, 443);
            DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

            try {
                try {
                    SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory ssf = sslcontext.getSocketFactory();
                    Socket socket = ssf.createSocket();
                    socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                    conn.bind(socket, params);

                    BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                            twitter_endpoint_path);

                    // need to add status parameter to this POST
                    MultipartEntity reqEntity = new MultipartEntity();

                    FileBody sb_image = new FileBody(file);
                    reqEntity.addPart("media", sb_image);

                    request2.setEntity(reqEntity);
                    request2.setParams(params);

                    request2.addHeader("Authorization", authorization_header_string);
                    System.out.println(
                            "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                    System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
                    response2.setParams(params);
                    httpexecutor.postProcess(response2, httpproc, context);
                    String responseBody = EntityUtils.toString(response2.getEntity());
                    System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
                    // error checking here. Otherwise, status should be updated.
                    jsonresponse = new JSONObject(responseBody);
                    if (jsonresponse.has("errors")) {
                        JSONObject temp_jo = new JSONObject();
                        temp_jo.put("response_status", "error");
                        temp_jo.put("message",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
                        temp_jo.put("twitter_code",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
                        jsonresponse = temp_jo;
                    }

                    // add it to the media_ids string
                    ids += jsonresponse.getString("media_id_string");
                    if (i != pics.length - 1) {
                        ids += ",";
                    }

                    conn.close();
                } catch (HttpException he) {
                    System.out.println(he.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia HttpException message=" + he.getMessage());
                    return null;
                } catch (NoSuchAlgorithmException nsae) {
                    System.out.println(nsae.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
                    return null;
                } catch (KeyManagementException kme) {
                    System.out.println(kme.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
                    return null;
                } finally {
                    conn.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
                return null;
            }
        } catch (Exception e) {
            return null;
        }

    }
    return ids;
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Setup SSL connection.//from  ww  w . j ava  2 s  .c  o m
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Load custom SSL certificates");
    }

    final SSLContext sslContext;
    try {
        // Load SSL certificates:
        // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
        // Earlier Android versions do not have updated root CA
        // certificates, resulting in connection errors.
        final KeyStore keyStore = loadCertificates(context);

        final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
        final TrustManager[] tms = new TrustManager[] { customTrustManager };

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tms, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}

From source file:org.eurekastreams.server.service.actions.strategies.links.ConnectionFacade.java

/**
 * Get the connection.//from w w  w  .ja va  2s .c  om
 *
 * @param inUrl
 *            the url.
 * @param inAccountId
 *            account id of the user making the request.
 * @return the connection.
 * @throws MalformedURLException
 *             If the URL is invalid.
 */
protected HttpURLConnection getConnection(final String inUrl, final String inAccountId)
        throws MalformedURLException {
    HttpURLConnection connection = null;

    if (proxyHost.length() > 0) {
        System.setProperty("https.proxyHost", proxyHost);
        System.setProperty("https.proxyPort", proxyPort);
    }

    log.info("Using Proxy: " + proxyHost + ":" + proxyPort);

    URL url = getUrl(inUrl);
    try {
        // Some sites e.g. Google Images and Digg will not respond to an unrecognized User-Agent.

        if ("https".equals(url.getProtocol())) {
            log.trace("Using HTTPS");

            // Install the all-trusting trust manager
            try {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                log.trace("Installed all-trusting trust manager.");
            } catch (Exception e) {
                log.error("Error setting SSL Context");
            }

            connection = (HttpsURLConnection) url.openConnection();

            ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String hostname, final SSLSession session) {
                    log.trace("Accepting host name.");
                    return true;
                }
            });
        } else {
            URLConnection plainConnection = url.openConnection();

            if (plainConnection instanceof HttpURLConnection) {
                log.trace("Using HTTP");
                connection = (HttpURLConnection) plainConnection;
            } else {
                log.info("Closing non-HTTP connection.");
                return null;
            }
        }

        connection.setConnectTimeout(connectionTimeOut);

        // Decorate the connection.
        for (ConnectionFacadeDecorator decorator : decorators) {
            decorator.decorate(connection, inAccountId);
        }
    } catch (Exception e) {
        log.error("caught exception: ", e);
    }

    return connection;
}

From source file:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

private SSLSocketFactory getSSLSocketFactory(String sslProtocol, String alias, KeyManager[] keyManagers,
        TrustManager[] trustManagers) throws KeyManagementException, NoSuchAlgorithmException {

    if (ArrayUtils.isNotEmpty(keyManagers)) {
        for (int i = 0; i < keyManagers.length; i++) {
            if (keyManagers[i] instanceof X509KeyManager) {
                keyManagers[i] = new AliasSelectorKeyManager((X509KeyManager) keyManagers[i], alias);
            }//from  w ww  .  j a  va2s . c o m
        }
    }

    SSLContext context = SSLContext.getInstance(sslProtocol);
    context.init(keyManagers, trustManagers, null);

    return context.getSocketFactory();
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private SSLSocketFactory generateSSLContextFromPEMCertString(String pemCert) {
    if (StringUtils.isNotBlank(pemCert) && pemCert.startsWith(BEGIN_CERT)) {
        try {/*from  ww w.ja va  2s  .  com*/
            InputStream certInputStream = IOUtils.toInputStream(pemCert);
            final X509Certificate trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(certInputStream);

            final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {

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

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                        throws CertificateException {
                    if (!certs[0].equals(trustedCert)) {
                        throw new CertificateException();
                    }
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                        throws CertificateException {
                    if (!certs[0].equals(trustedCert)) {
                        throw new CertificateException();
                    }
                }
            } };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManager, new java.security.SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            logger.error("A NoSuchAlgorithmException occurred: ", e);
        } catch (KeyManagementException e) {
            logger.error("A KeyManagementException occurred: ", e);
        } catch (CertificateException e) {
            logger.error("A CertificateException occurred: ", e);
        }
    } else {
        logger.error("Cert is empty");
    }
    return null;
}

From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsWithSSLDUnitTest.java

public void testSSLWithCipherSuite() throws Exception {

    System.setProperty("javax.net.debug", "ssl");
    Properties props = new Properties();
    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "TLSv1.2");

    SSLContext ssl = SSLContext.getInstance("TLSv1.2");

    ssl.init(null, null, new java.security.SecureRandom());
    String[] cipherSuites = ssl.getSocketFactory().getSupportedCipherSuites();

    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_CIPHERS_NAME, cipherSuites[0]);

    String restEndpoint = startInfraWithSSL(props, false);
    validateConnection(restEndpoint, "TLSv1.2");

}

From source file:com.gemstone.gemfire.rest.internal.web.controllers.RestAPIsWithSSLDUnitTest.java

public void testSSLWithMultipleCipherSuite() throws Exception {

    Properties props = new Properties();
    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_ENABLED_NAME, "true");
    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_NAME, jks.getCanonicalPath());
    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_KEYSTORE_PASSWORD_NAME, "password");
    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_PROTOCOLS_NAME, "TLSv1.2");

    SSLContext ssl = SSLContext.getInstance("TLSv1.2");

    ssl.init(null, null, new java.security.SecureRandom());
    String[] cipherSuites = ssl.getSocketFactory().getSupportedCipherSuites();

    props.setProperty(DistributionConfig.HTTP_SERVICE_SSL_CIPHERS_NAME,
            cipherSuites[0] + "," + cipherSuites[1]);

    String restEndpoint = startInfraWithSSL(props, false);
    validateConnection(restEndpoint, "TLSv1.2");

}

From source file:org.parosproxy.paros.network.SSLConnector.java

public void setActiveCertificate() {

    SSLContext sslcont = sslContextManager.getSSLContext(sslContextManager.getDefaultKey());
    clientSSLSockCertFactory = createDecoratedClientSslSocketFactory(sslcont.getSocketFactory());
    logger.info("ActiveCertificate set to: " + sslContextManager.getDefaultKey());
}