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:com.mgmtp.perfload.core.client.web.config.HttpClientManagerModule.java

/**
 * If the property {@code ssl.trust.all} equals {@code true}, a {@link TrustAllManager} is
 * installed, i. e. all certificates are trusted, and host name verification is turned off.
 * Otherwise, {@link LtSSLSocketFactory} is registered for HTTPS, if either a key store, a trust
 * store or both are configured using the following properties:</p>
 * <p>//from  w  w  w. j a  va2  s  .c om
 * <ul>
 * <li>{@code javax.net.ssl.keyStore}</li>
 * <li>{@code javax.net.ssl.keyStorePassword}</li>
 * <li>{@code javax.net.ssl.keyStoreType}</li>
 * <li>{@code javax.net.ssl.trustStore}</li>
 * <li>{@code javax.net.ssl.trustStorePassword}</li>
 * <li>{@code javax.net.ssl.trustStoreType}</li>
 * </ul>
 * </p>
 * <p>
 * {@code javax.net.ssl.trustStore} and {@code javax.net.ssl.keyStore} must point to resources
 * on the classpath.
 * </p>
 * 
 * @param properties
 *            the properties
 * @return the {@link SchemeRegistry} the SchemeRegistry used for the HttpClient's
 *         {@link ClientConnectionManager} registered for HTTPS
 */
@Provides
@Singleton
protected SchemeRegistry provideSchemeRegistry(final PropertiesMap properties) {
    SchemeRegistry registry = SchemeRegistryFactory.createDefault();

    if (properties.getBoolean(SSL_TRUST_ALL)) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new TrustAllManager() }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, new AllowAllHostnameVerifier());
            registry.register(new Scheme("https", 443, ssf));
        } catch (GeneralSecurityException ex) {
            Throwables.propagate(ex);
        }
    } else {
        String keyStore = trimToNull(properties.get(KEY_STORE));
        String trustStore = trimToNull(properties.get(TRUST_STORE));

        if (keyStore != null || trustStore != null) {
            String keyStorePassword = trimToNull(properties.get(KEY_STORE_PASSWORD));
            String keyStoreType = trimToNull(properties.get(KEY_STORE_TYPE));

            String trustStorePassword = trimToNull(properties.get(TRUST_STORE_PASSWORD));
            String trustStoreType = trimToNull(properties.get(TRUST_STORE_TYPE));

            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            URL keyStoreUrl = keyStore != null ? loader.getResource(keyStore) : null;
            URL trustStoreUrl = trustStore != null ? loader.getResource(trustStore) : null;

            LayeredSchemeSocketFactory socketFactory = new LtSSLSocketFactory(keyStoreUrl, keyStorePassword,
                    keyStoreType, trustStoreUrl, trustStorePassword, trustStoreType);

            registry.register(new Scheme(HTTPS, 443, socketFactory));
        }
    }
    return registry;
}

From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(APIConfiguration pConfiguration) {

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory(
            new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory());

    SSLContext oSslContext = null;
    X509HostnameVerifier oHostnameVerifier = null;
    if (pConfiguration.isCheckSSLCertificates()) {
        oSslContext = SSLContexts.createSystemDefault();
        oHostnameVerifier = new BrowserCompatHostnameVerifier();
    } else {//from  w ww . ja  va  2  s .co  m
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

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

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

        // Install the all-trusting trust manager
        try {
            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();
            oSslContext = sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new APIClientException(e);
        } catch (KeyManagementException e) {
            throw new APIClientException(e);
        }
        oHostnameVerifier = new AllowAllHostnameVerifier();
    }

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTP, PlainConnectionSocketFactory.INSTANCE)
            .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* {
                                                               @Override
                                                               public InetAddress[] resolve(final String host) throws UnknownHostException {
                                                               if (host.equalsIgnoreCase("myhost")) {
                                                               return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
                                                               } else {
                                                               return super.resolve(host);
                                                               }
                                                               }
                                                               };*/

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager(
            oSocketFactoryRegistry, oConnFactory, oDnsResolver);

    // Create socket configuration
    SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true)
            .setSoTimeout(pConfiguration.getSocketTimeout()).build();

    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    oConnManager.setDefaultSocketConfig(oSocketConfig);
    // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig);

    // Create message constraints
    MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig oConnectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(oMessageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    oConnManager.setDefaultConnectionConfig(oConnectionConfig);
    // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    oConnManager.setMaxTotal(100);
    oConnManager.setDefaultMaxPerRoute(10);
    //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore oCookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    //
    // Create global request configuration
    RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            //.setExpectContinueEnabled(true)         // WARNING: setting it to true slows things down by 4s!!!!
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(pConfiguration.getConnectionTimeout()).build();

    CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider();
    HttpHost oProxy = null;

    if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) {
        String proxyHost = pConfiguration.getProxyHost();
        int proxyPort = pConfiguration.getProxyPort();
        String proxyUsername = pConfiguration.getProxyUsername();
        String proxyPassword = pConfiguration.getProxyPassword();
        String proxyDomain = pConfiguration.getProxyDomain();
        String proxyWorkstation = pConfiguration.getProxyWorkstation();

        oProxy = new HttpHost(proxyHost, proxyPort);

        if (proxyUsername != null && proxyPassword != null) {
            oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager)
            .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider)
            .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build();

    return oHttpClient;
    /*
    RequestConfig oRequestConfig = RequestConfig.custom()
    .setConnectTimeout(pConfiguration.getConnectionTimeout())
    .setSocketTimeout(pConfiguration.getSocketTimeout())
    .setStaleConnectionCheckEnabled(true)
    .build();
    */
}

From source file:org.wso2.carbon.databridge.agent.thrift.internal.pool.client.secure.SecureClientPoolFactory.java

@Override
public ThriftSecureEventTransmissionService.Client makeObject(Object key)
        throws AgentSecurityException, TTransportException {
    String[] keyElements = key.toString().split(AgentConstants.SEPARATOR);
    if (keyElements[2].equals(ReceiverConfiguration.Protocol.TCP.toString())) {
        if (params == null) {
            if (trustStore == null) {
                trustStore = System.getProperty("javax.net.ssl.trustStore");
                if (trustStore == null) {
                    throw new AgentSecurityException("No trustStore found");
                }/* w w  w .  j ava 2  s .co  m*/
                // trustStore = "/home/suho/projects/wso2/trunk/carbon/distribution/product/modules/distribution/target/wso2carbon-4.0.0-SNAPSHOT/repository/resources/security/client-truststore.jks";
            }

            if (trustStorePassword == null) {
                trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
                if (trustStorePassword == null) {
                    throw new AgentSecurityException("No trustStore password found");
                }
                //trustStorePassword = "wso2carbon";
            }

            params = new TSSLTransportFactory.TSSLTransportParameters();
            params.setTrustStore(trustStore, trustStorePassword);
        }

        String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR);

        TTransport receiverTransport = null;
        try {
            receiverTransport = TSSLTransportFactory.getClientSocket(
                    HostAddressFinder.findAddress(hostNameAndPort[0]), Integer.parseInt(hostNameAndPort[1]), 0,
                    params);
        } catch (SocketException ignored) {
            //already checked
        }

        TProtocol protocol = new TBinaryProtocol(receiverTransport);
        return new ThriftSecureEventTransmissionService.Client(protocol);
    } else {
        try {
            TrustManager easyTrustManager = new X509TrustManager() {
                public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                        throws java.security.cert.CertificateException {
                }

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

                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            String[] hostNameAndPort = keyElements[3].split(AgentConstants.HOSTNAME_AND_PORT_SEPARATOR);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslContext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(hostNameAndPort[1]));

            DefaultHttpClient client = new DefaultHttpClient();
            client.getConnectionManager().getSchemeRegistry().register(httpsScheme);

            THttpClient tclient = new THttpClient("https://" + keyElements[3] + "/securedThriftReceiver",
                    client);
            TProtocol protocol = new TCompactProtocol(tclient);
            ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client(
                    protocol);
            tclient.open();
            return authClient;
        } catch (Exception e) {
            throw new AgentSecurityException("Cannot create Secure client for " + keyElements[3], e);
        }
    }
}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.java

/**
 * Constructor for StrictSSLProtocolSocketFactory.
 * Host name verification will be enabled by default.
 * @throws NoSuchAlgorithmException //from ww  w .  ja v a2 s.  c  o m
 */
public StrictSSLProtocolSocketFactory() throws NoSuchAlgorithmException {
    super(SSLContext.getInstance("SSL"));
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * @description javaSSLContext//ww  w  . j a v a2  s .c o m
 * @description https?, SSLContext (NoHttp?SecureRandombug)
 * @description client.ks?server
 * @description ??
 * @description ????getSSLContext2()
 */
//@SuppressLint("TrulyRandom")
public static SSLContext getSSLContext() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        // ??, ??assets
        InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks"));
        //App.getInstance().getAssets().open("srca.cer");

        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");

        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(inputStream, "123456".toCharArray());
        //Certificate cer = cerFactory.generateCertificate(inputStream);
        Certificate cer = keyStore.getCertificate("clientKey");
        keyStore.setCertificateEntry("trust", cer);

        // KeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "123456".toCharArray());

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        // ?SSLContext
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:talkeeg.httpserver.HttpServer.java

private NHttpConnectionFactory<DefaultNHttpServerConnection> createConnectionFactory() {
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (config.isUseTLS()) {
        try {//w ww.j  ava2s .c  o m
            KeyStore keystore = KeyStore.getInstance("jks");
            char[] password = new char[0];
            keystore.load(null, password);
            final X509Certificate certificate = certManager.getCertificate(OwnedKeyType.USER);
            KeyStore.PrivateKeyEntry entry = new KeyStore.PrivateKeyEntry(
                    ownedKeysManager.getPrivateKey(OwnedKeyType.USER), new Certificate[] { certificate });

            keystore.setEntry("", entry, new KeyStore.PasswordProtection(password));
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, password);
            final KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException("Can not initialise SSL.", e);
        }
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    return connFactory;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private void addSslConnection(URLConnection connection) {
    if (connection instanceof HttpsURLConnection) {
        try {//from w  ww .  j a v  a 2 s.  c  om
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { new AcceptAllTrustManager() }, new SecureRandom());
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new AcceptAllHostnameVerifier());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.socialbiz.cog.util.SSLPatch.java

/**
* a call to disableSSLCertValidation will disable certificate validation
* for SSL connection made after this call.   This is installed as the
* default in the JVM for future calls./*  ww w  . j  a v a 2s.  co m*/
*
* Returns the properly initialized SSLContext in case it is needed for
* something else (like Apache HttpClient libraries) but if you don't need
* it you can ignore it.
*/
public static SSLContext disableSSLCertValidation() throws Exception {

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { getDummyTrustManager() };

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(getAllHostVerifier());

    return sc;
}

From source file:at.diamonddogs.net.SSLHelper.java

/**
 * Register a keystore with SSL (JAVA)//from  w  ww  .  j a va  2  s .c  o m
 * 
 * @param c
 *            a {@link Context}
 * @param resourceId
 *            the resource id of the keystore
 * @param password
 *            the password of the keystore
 * @return true on success, false otherwise
 */
public boolean initSSLFactoryJava(Context c, int resourceId, String password) {
    try {
        if (c == null || resourceId == -1 || password == null) {
            LOGGER.info("No keystore specified, using alltrust");
            makeAllTrustManagerForJava();
            return true;
        } else {
            KeyStore store = getKeyStore(c, resourceId, password);
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(store);
            SSLContext sslCtx = SSLContext.getInstance("TLS");
            sslCtx.init(null, tmf.getTrustManagers(), null);
            SSL_FACTORY_JAVA = sslCtx.getSocketFactory();
            sslState.trustAll = false;
            return true;
        }
    } catch (Throwable tr) {
        LOGGER.warn("Error initializing SSLFactoryJava", tr);
        try {
            makeAllTrustManagerForJava();
            sslState.tr = tr;
            return true;
        } catch (Throwable tr1) {
            sslState.tr1 = tr1;
            sslState.sslOk = false;
            LOGGER.warn("Error trusting all certs, no ssl connection possible", tr);
        }
        return false;
    }
}