Example usage for javax.net.ssl SSLContext getInstance

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

Introduction

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

Prototype

public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SSLContext object that implements the specified secure socket protocol.

Usage

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

/**
 * @param options//from  w ww  .j a v a 2s .  c  o  m
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws KeyManagementException
 * @throws UnrecoverableKeyException
 */
public static void init(BasicSignerOptions options) throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
    KeyManager[] km = null;
    if (options != null && options.getTsaServerAuthn() == ServerAuthentication.CERTIFICATE) {
        char[] pwd = null;
        if (StringUtils.isNotEmpty(options.getTsaCertFilePwd())) {
            pwd = options.getTsaCertFilePwd().toCharArray();
        }
        LOGGER.info(Constants.RES.get("ssl.keymanager.init", options.getTsaCertFile()));
        final String ksType = StringUtils.defaultIfBlank(options.getTsaCertFileType(), "PKCS12");
        KeyStore keyStore = KeyStoreUtils.loadKeyStore(ksType, options.getTsaCertFile(), pwd);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, pwd);
        km = keyManagerFactory.getKeyManagers();
    }
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(km, TRUST_MANAGERS, null);

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

From source file:com.villemos.ispace.webster.WebsterProducer.java

public void process(Exchange exchange) throws Exception {

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {/*  ww  w . j  a v  a 2s.c  om*/
        client = new DefaultHttpClient();
    }

    String proxyHost = getWebsterEndpoint().getProxyHost();
    Integer proxyPort = getWebsterEndpoint().getProxyPort();

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (getWebsterEndpoint().getAuthenticationUser() != null
            && getWebsterEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort()),
                new UsernamePasswordCredentials(getWebsterEndpoint().getAuthenticationUser(),
                        getWebsterEndpoint().getAuthenticationPassword()));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    String uriStr = getWebsterEndpoint().getProtocol() + "://" + getWebsterEndpoint().getDomain() + "/"
            + getWebsterEndpoint().getPath();
    if (getWebsterEndpoint().getPort() != 80) {
        uriStr += ":" + getWebsterEndpoint().getPort() + "/" + getWebsterEndpoint().getPath();
    }

    /** Break the query into its elements and search for each. */
    for (String word : ((String) exchange.getIn().getHeader(SolrOptions.query)).split("\\s+")) {
        uriStr += "/" + word;
        URI uri = new URI(uriStr);

        if (getWebsterEndpoint().getPort() != 80) {
            target = new HttpHost(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort(),
                    getWebsterEndpoint().getProtocol());
        } else {
            target = new HttpHost(getWebsterEndpoint().getDomain());
        }
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpUriRequest method = new HttpGet(uri);
        HttpResponse response = client.execute(target, method, localContext);

        if (response.getStatusLine().getStatusCode() == 200) {
            /** Extract result. */
            String page = HttpClientConfigurer.readFully(response.getEntity().getContent());

            ResultSet set = new ResultSet();

            Matcher matcher = pattern.matcher(page);
            if (matcher.find()) {
                String result = matcher.group(1).replaceAll("\\<.*?\\>", "").replaceAll("\\s+", " ");

                /** Create ResultSet*/
                InformationObject io = new InformationObject();
                io.hasUri = uriStr;
                io.fromSource = "Webster";
                io.hasTitle = "Webster definition of '" + word + "'.";
                io.ofEntityType = "Definition";
                io.ofMimeType = "text/html";
                io.withRawText = result;
                io.score = 20;
                set.informationobjects.add(io);
            }

            matcher = spellPattern.matcher(page);
            if (matcher.find()) {
                String result = matcher.group(1);
                String[] elements = result.split("<li><a href=.*?>");

                for (String element : elements) {
                    if (element.trim().equals("") == false) {
                        set.suggestions
                                .add(new Suggestion(word, element.replaceAll("<.*?>", "").trim(), "Webster"));
                    }
                }
            }

            if (exchange.getIn().getHeader(SolrOptions.stream) != null) {

                for (InformationObject io : set.informationobjects) {
                    Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(io);
                    endpoint.getCamelContext().createProducerTemplate()
                            .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange);
                }

                for (Suggestion suggestion : set.suggestions) {
                    Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(suggestion);
                    endpoint.getCamelContext().createProducerTemplate()
                            .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange);
                }
            } else {
                exchange.getOut().setBody(set);
            }
        } else {
            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();
            String page = HttpClientConfigurer.readFully(response.getEntity().getContent());

            System.out.println(page);
        }
    }
}

From source file:com.adito.boot.CustomSSLSocketFactory.java

private SSLSocketFactory getSocketFactory() throws IOException {
    try {/*from  w  w w  .  j a v  a2 s.  c  o m*/
        SSLContext sslCtx = SSLContext.getInstance("SSL");
        KeyManager[] aKM = SSLKeyManager.getKeyManagerArray();
        TrustManager[] aTM = SSLTrustManager.getTrustManagerArray();
        sslCtx.init(aKM, aTM, null);
        SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
        return socketFactory;
    } catch (KeyManagementException e) {
        log.error("Cannot create SSL socket", e);
        throw new IOException("Cannot create SSL socket: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        log.error("Cannot create SSL socket", e);
        throw new IOException("Cannot create SSL socket: " + e.getMessage());
    }
}

From source file:it.publisys.liferay.hook.shibboleth.ShibbolethPostLogoutAction.java

/**
 * Effettua una {@link HttpURLConnection} inviando anche i cookies
 *
 * @param url     url/*from ww  w  .  j a  v  a  2s. c o m*/
 * @param cookies cookies
 * @return response code
 */
private int _connect(String url, String cookies) {
    int responseCode = -1;
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws CertificateException {
            }

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

        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }

    HttpURLConnection connection = null;
    try {
        URL _url = new URL(url);
        connection = (HttpURLConnection) _url.openConnection(Proxy.NO_PROXY);
        connection.setRequestProperty("Cookie", cookies);
        connection.setReadTimeout(5000);
        connection.setRequestMethod("GET");

        responseCode = connection.getResponseCode();
        _log.info("Logout Shibb response code: " + responseCode);

        if (responseCode == 200 && _log.isDebugEnabled()) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder _buffer = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    _buffer.append(line);
                }
                _log.debug(_buffer.toString());
            } finally {
                if (br != null) {
                    br.close();
                }
            }

        }

    } catch (MalformedURLException mue) {
        mue.printStackTrace(System.err);
    } catch (IOException ioe) {
        ioe.printStackTrace(System.err);
    } finally {
        try {
            if (connection != null) {
                connection.disconnect();
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }
    return responseCode;
}

From source file:com.ibm.watson.developer_cloud.android.speech_to_text.v1.audio.WebSocketUploader.java

/**
 * Trust server/*from www. j av  a  2s .  co  m*/
 *
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private void trustServer() throws KeyManagementException, NoSuchAlgorithmException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

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

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext sslContext = null;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, certs, new java.security.SecureRandom());
    this.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
}

From source file:com.t2auth.AuthUtils.java

public static SSLContext getSslContext(Context ctx) {
    InputStream in = null;/*from  ww w.  ja v a  2  s  . c o m*/

    if (sSslContext == null) {
        try {
            sSslContext = SSLContext.getInstance("TLS");
            try {
                if (sKey == null) {
                    sKey = KeyStore.getInstance("BKS");
                    in = ctx.getResources().openRawResource(R.raw.keystore);
                    sKey.load(in, "itsatrap".toCharArray());
                }

                TrustManagerFactory tmf = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(sKey);
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
                kmf.init(sKey, "itsatrap".toCharArray());

                sSslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
                return sSslContext;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    } else {
        return sSslContext;
    }

    return null;
}

From source file:com.careerly.utils.HttpClientUtils.java

/**
 * ??https/* www .java 2 s  .  c  o  m*/
 *
 * @param base
 * @return
 */
private static HttpClient wrapHttpsClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 443, ssf));
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
        return new DefaultHttpClient(mgr, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.kontalk.client.KontalkConnection.java

@SuppressLint("AllowAllHostnameVerifier")
private static void setupSSL(XMPPTCPConnectionConfiguration.Builder builder, boolean direct,
        PrivateKey privateKey, X509Certificate bridgeCert, boolean acceptAnyCertificate, KeyStore trustStore) {
    try {/*from   ww w  .  j a  v  a  2 s. c  o m*/
        SSLContext ctx = SSLContext.getInstance("TLS");

        KeyManager[] km = null;
        if (privateKey != null && bridgeCert != null) {
            // in-memory keystore
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert });

            // key managers
            KeyManagerFactory kmFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmFactory.init(keystore, null);

            km = kmFactory.getKeyManagers();

            // disable PLAIN mechanism if not upgrading from legacy
            if (!LegacyAuthentication.isUpgrading()) {
                // blacklist PLAIN mechanism
                SASLAuthentication.blacklistSASLMechanism("PLAIN");
            }
        }

        // trust managers
        TrustManager[] tm;

        if (acceptAnyCertificate) {
            tm = new TrustManager[] { new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
            } };
            builder.setHostnameVerifier(new AllowAllHostnameVerifier());
        }

        else {
            // builtin keystore
            TrustManagerFactory tmFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmFactory.init(trustStore);

            tm = tmFactory.getTrustManagers();
        }

        ctx.init(km, tm, null);
        builder.setCustomSSLContext(ctx);
        if (direct)
            builder.setSocketFactory(ctx.getSocketFactory());

        // SASL EXTERNAL is already enabled in Smack
    } catch (Exception e) {
        Log.w(TAG, "unable to setup SSL connection", e);
    }
}

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

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams arg4) throws IOException, UnknownHostException, ConnectTimeoutException {
    TrustManager[] trustAllCerts = getTrustManager();

    try {/*from w  w  w  .  j a v  a  2s  .  com*/

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

    }

}