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:org.wso2.carbon.apimgt.gateway.handlers.security.thrift.ThriftAuthClient.java

public ThriftAuthClient(String serverIP, String remoteServerPort, String webContextRoot)
        throws AuthenticationException {

    try {/*from  w  ww  .j av  a 2s .c  o m*/
        TrustManager easyTrustManager = new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
            }

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

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

        //skip host name verification
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        //REGISTERS SCHEMES FOR BOTH HTTP AND HTTPS
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", sf, Integer.parseInt(remoteServerPort)));

        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        HttpClient httpClient = new DefaultHttpClient(manager);

        //If the webContextRoot is null or /
        if (webContextRoot == null || "/".equals(webContextRoot)) {
            //Assign it an empty value since it is part of the thriftServiceURL.
            webContextRoot = "";
        }
        String thriftServiceURL = "https://" + serverIP + ':' + remoteServerPort + webContextRoot + '/'
                + "thriftAuthenticator";
        client = new THttpClient(thriftServiceURL, httpClient);

    } catch (TTransportException e) {
        throw new AuthenticationException("Error in creating thrift authentication client..", e);
    } catch (Exception e) {
        throw new AuthenticationException("Error in creating thrift authentication client..", e);
    }
}

From source file:com.alvexcore.share.ShareExtensionRegistry.java

@Override
public void afterPropertiesSet() throws Exception {
    // disable SSL certs validation
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from  w w  w .  jav  a 2 s . c om*/
        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) {
        }
    } };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

From source file:com.ring.ytjojo.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//from   w w  w. ja  va 2s  .  co m

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = AppContext_.getInstance().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the 
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = AppContext_.getInstance().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:br.com.anteros.sms.modem.IPModemDriver.java

@Override
protected void connectPort() throws GatewayException, IOException, InterruptedException {
    try {/*from w  w w . java 2 s .  com*/
        Logger.getInstance().logInfo("Opening: " + this.ipAddress + " @" + this.ipPort, null,
                getGateway().getGatewayId());
        this.tc = new TelnetClient();
        this.tc.addOptionHandler(this.ttopt);
        this.tc.addOptionHandler(this.echoopt);
        this.tc.addOptionHandler(this.gaopt);
        if (getGateway().getIpProtocol() == IPProtocols.BINARY)
            this.tc.addOptionHandler(this.binaryopt); // Make telnet session binary, so ^Z in ATHander.Sendmessage is send raw!
        if (getGateway().getIpEncryption()) {
            try {
                this.tc.setSocketFactory(SSLContext.getInstance("Default").getSocketFactory());
            } catch (NoSuchAlgorithmException e) {
                Logger.getInstance().logError("Unable to find algorithm needed for using SSL", e,
                        getGateway().getGatewayId());
                // TODO: although not supposed to happen, something should be done if it does
            }
        }
        this.tc.connect(this.ipAddress, this.ipPort);
        this.in = this.tc.getInputStream();
        this.out = this.tc.getOutputStream();
        this.peeker = new Peeker();
    } catch (InvalidTelnetOptionException e) {
        throw new GatewayException("Unsupported telnet option for the selected IP connection.");
    }
}

From source file:com.msopentech.thali.utilities.universal.HttpKeySSLSocketFactory.java

public HttpKeySSLSocketFactory(final PublicKey serverPublicKey, final KeyStore clientKeyStore,
        final char[] clientPassPhrase)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    super((KeyStore) null);

    final ThaliPublicKeyComparer thaliPublicKeyComparer = serverPublicKey == null ? null
            : new ThaliPublicKeyComparer(serverPublicKey);

    TrustManager trustManager = new X509TrustManager() {
        @Override/* w  w  w. j  a v  a2  s . co  m*/
        public void checkClientTrusted(X509Certificate[] x509Certificates, String authType)
                throws CertificateException {
            throw new RuntimeException(
                    "We should not have gotten a client trusted call, authType was:" + authType);
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String authType)
                throws CertificateException {
            //TODO: We actually need to restrict authTypes to known secure ones
            if (serverPublicKey == null) {
                return;
            }
            PublicKey rootPublicKey = x509Certificates[x509Certificates.length - 1].getPublicKey();
            if (thaliPublicKeyComparer.KeysEqual(rootPublicKey) == false) {
                throw new RuntimeException("Presented server root key does not match expected server root key");
            }
        }

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

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(clientKeyStore, clientPassPhrase);

    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { trustManager },
            new SecureRandom());
    this.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java

/**
 * Factory method that builds a new SSLConnectionSocketFactory.
 * @param options the current WebClientOptions
 * @return the SSLConnectionSocketFactory
 *//*from  w w w . j  a v  a2 s . c  o  m*/
public static SSLConnectionSocketFactory buildSSLSocketFactory(final WebClientOptions options) {
    try {
        final String[] sslClientProtocols = options.getSSLClientProtocols();
        final String[] sslClientCipherSuites = options.getSSLClientCipherSuites();

        final boolean useInsecureSSL = options.isUseInsecureSSL();

        if (!useInsecureSSL) {
            final KeyStore keyStore = options.getSSLClientCertificateStore();
            final KeyStore trustStore = options.getSSLTrustStore();

            return new HtmlUnitSSLConnectionSocketFactory(keyStore,
                    keyStore == null ? null : options.getSSLClientCertificatePassword(), trustStore,
                    useInsecureSSL, sslClientProtocols, sslClientCipherSuites);
        }

        // we need insecure SSL + SOCKS awareness
        String protocol = options.getSSLInsecureProtocol();
        if (protocol == null) {
            protocol = "SSL";
        }
        final SSLContext sslContext = SSLContext.getInstance(protocol);
        sslContext.init(getKeyManagers(options), new TrustManager[] { new InsecureTrustManager2() }, null);

        final SSLConnectionSocketFactory factory = new HtmlUnitSSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE, useInsecureSSL, sslClientProtocols, sslClientCipherSuites);
        return factory;
    } catch (final GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.dacas.emmclient.security.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//from ww  w .  ja va  2s  . co m

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = EmmClientApplication.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the 
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = EmmClientApplication.getContext().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:com.ldroid.kwei.common.lib.volley.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {/*w  w  w .j av  a 2 s. c  om*/

        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = MainApp.getContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = MainApp.getContext().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:org.pluroid.pluroium.HttpClientFactory.java

/**
 * Constructor/*from   w w w  . jav a2 s .c om*/
 */
public MySSLSocketFactory() {
    if (m_sslSocketFactory == null) {
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, null, null);
            m_sslSocketFactory = sc.getSocketFactory();
        } catch (Exception ex) {
        }
    }
}

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.thrift.ThriftAuthClient.java

public ThriftAuthClient(String serverIP, String remoteServerPort, String webContextRoot)
        throws AuthenticationException {
    try {/*from  w w  w . j av a2  s  .  c  o  m*/
        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;
            }
        };

        //skip host name verification
        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(remoteServerPort));

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

        //If the webContextRoot is null or /
        if (webContextRoot == null || "/".equals(webContextRoot)) {
            //Assign it an empty value since it is part of the thriftServiceURL.
            webContextRoot = "";
        }
        String thriftServiceURL = "https://" + serverIP + ":" + remoteServerPort + webContextRoot + "/"
                + "thriftAuthenticator";
        client = new THttpClient(thriftServiceURL, httpClient);

    } catch (TTransportException e) {
        throw new AuthenticationException("Error in creating thrift authentication client..");
    } catch (Exception e) {
        throw new AuthenticationException("Error in creating thrift authentication client..");
    }
}