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.dataone.proto.trove.net.SocketFactoryManager.java

public SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, UnrecoverableKeyException,
        KeyStoreException, KeyManagementException, CertificateException, IOException {
    // our return object
    log.debug("Enter getSSLSocketFactory");
    SSLSocketFactory socketFactory = null;
    KeyStore keyStore = null;//from www. j  av a 2s. com

    // get the keystore that will provide the material
    // Catch the exception here so that the TLS connection scheme
    // will still be setup if the client certificate is not found.
    try {
        keyStore = getKeyStore();
    } catch (FileNotFoundException e) {
        // these are somewhat expected for anonymous d1 client use
        log.warn(
                "Could not set up client side authentication - likely because the certificate could not be located: "
                        + e.getMessage());
    }

    // create SSL context
    SSLContext ctx = SSLContext.getInstance("TLS");

    // use a very liberal trust manager for trusting the server
    // TODO: check server trust policy
    X509TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            log.info("checkClientTrusted - " + string);
        }

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            log.info("checkServerTrusted - " + string);
        }

        public X509Certificate[] getAcceptedIssuers() {
            log.info("getAcceptedIssuers");
            return null;
        }
    };

    // specify the client key manager
    KeyManager[] keyManagers = { new X509KeyManagerImpl(keyStore, keyStorePassword.toCharArray(), "cilogon") };
    //        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    //        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    //        keyManagers = keyManagerFactory.getKeyManagers();

    // initialize the context
    ctx.init(keyManagers, new TrustManager[] { tm }, new SecureRandom());
    socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    return socketFactory;
}

From source file:org.wso2.carbon.databridge.agent.internal.endpoint.thrift.client.ThriftSecureClientPoolFactory.java

@Override
public Object createClient(String protocol, String hostName, int port)
        throws DataEndpointAgentSecurityException {
    String trustStore, trustStorePw;
    if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.TCP.toString())) {
        if (params == null) {
            if (getTrustStore() == null) {
                trustStore = System.getProperty("javax.net.ssl.trustStore");
                if (trustStore == null) {
                    throw new DataEndpointAgentSecurityException("No trustStore found");
                } else {
                    setTrustStore(trustStore);
                }/*from ww  w . ja  v  a2 s  . co m*/
            }

            if (getTrustStorePassword() == null) {
                trustStorePw = System.getProperty("javax.net.ssl.trustStorePassword");
                if (trustStorePw == null) {
                    throw new DataEndpointAgentSecurityException("No trustStore password found");
                } else {
                    setTrustStorePassword(trustStorePw);
                }
            }

            params = new TSSLTransportFactory.TSSLTransportParameters();
            params.setTrustStore(getTrustStore(), getTrustStorePassword());
        }

        TTransport receiverTransport = null;
        try {
            receiverTransport = TSSLTransportFactory.getClientSocket(hostName, port, 0, params);
            TProtocol tProtocol = new TBinaryProtocol(receiverTransport);
            return new ThriftSecureEventTransmissionService.Client(tProtocol);
        } catch (TTransportException e) {
            throw new DataEndpointAgentSecurityException(
                    "Error while trying to connect to " + protocol + "://" + hostName + ":" + port, e);
        }
    } else {
        //TODO:Error  thrown when connecting in http in tests...
        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;
                }
            };
            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, port);

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

            THttpClient tclient = new THttpClient("https://" + hostName + ":" + port + "/securedThriftReceiver",
                    client);
            TProtocol tProtocol = new TCompactProtocol(tclient);
            ThriftSecureEventTransmissionService.Client authClient = new ThriftSecureEventTransmissionService.Client(
                    tProtocol);
            tclient.open();
            return authClient;
        } catch (Exception e) {
            throw new DataEndpointAgentSecurityException("Cannot create Secure client for " + "https://"
                    + hostName + ":" + port + "/securedThriftReceiver", e);
        }
    }
}

From source file:org.wso2.carbon.identity.thrift.authentication.client.internal.pool.SecureClientPoolFactory.java

@Override
public AuthenticatorService.Client makeObject(Object key)
        throws ThriftAuthenticationException, TTransportException {
    String[] keyElements = constructKeyElements((String) key);
    if (keyElements[0].equals(ThriftAuthenticationClient.Protocol.SSL.toString())) {
        if (params == null) {
            if (trustStore == null) {
                trustStore = System.getProperty("javax.net.ssl.trustStore");
                if (trustStore == null) {
                    throw new ThriftAuthenticationException("No trustStore found");
                }//from w ww.j av a  2s.c  o  m
            }

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

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

        TTransport receiverTransport = TSSLTransportFactory.getClientSocket(keyElements[1],
                Integer.parseInt(keyElements[2]), 0, params);

        TProtocol protocol = new TBinaryProtocol(receiverTransport);
        return new AuthenticatorService.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(ThriftAuthenticationClientConstants.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(keyElements[2]));

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

            THttpClient tclient = new THttpClient(
                    "https://" + keyElements[1] + ":" + keyElements[2] + "/thriftAuthenticator", client);
            TProtocol protocol = new TCompactProtocol(tclient);
            AuthenticatorService.Client authClient = new AuthenticatorService.Client(protocol);
            tclient.open();
            return authClient;
        } catch (Exception e) {
            throw new ThriftAuthenticationException(
                    "Cannot create Secure client for " + keyElements[1] + ":" + keyElements[2], e);
        }
    }
}

From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java

public OverviewServlet(TemplateRenderer templateRenderer, JiraAuthenticationContext authenticationContext,
        PluginSettingsFactory settingsFactory, ApplicationProperties applicationProperties) {
    this.templateRenderer = templateRenderer;
    this.authenticationContext = authenticationContext;
    this.serverList = new ServerList(settingsFactory);
    this.client = new HttpClient(new MultiThreadedHttpConnectionManager());

    //test if jiraversion < 4.3
    IsPriorToJiraVersion isPrior = new IsPriorToJiraVersion(applicationProperties);
    isPrior.setmaxMajorVersion(4);/*from w  w  w  . j a  v  a  2  s.  c  om*/
    isPrior.setmaxMinorVersion(3);
    this.old = isPrior.shouldDisplay(null);

    client.getParams().setAuthenticationPreemptive(true);

    //set SSLContext to accept all certificates
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SecureProtocolSocketFactory secureProtocolSocketFactory = new SSLProtocolSocketFactory();

    Protocol.registerProtocol("https",
            new Protocol("https", (ProtocolSocketFactory) secureProtocolSocketFactory, 443));
}

From source file:org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule.java

@Singleton
@Provides/*from  w  ww  .  j  a  va2 s  .com*/
final SSLContext newSSLContext(HttpUtils utils,
        @Named("untrusted") Supplier<SSLContext> untrustedSSLContextProvider)
        throws NoSuchAlgorithmException, KeyManagementException {
    if (utils.trustAllCerts())
        return untrustedSSLContextProvider.get();
    SSLContext context = SSLContext.getInstance("TLS");

    context.init(null, null, null);
    return context;
}

From source file:it.haefelinger.flaka.util.InitSSL.java

static public void install(TrustManager tm) throws Exception {
    // There's a problem (bug?) in Java 1.4 causing sc.init() to take a
    // very long time. Disabling installation of new trustmanager if
    // not 1.5 or newer. That's just fine cause 1.4 trustmanger accepts
    // self signed certificates.
    if (isjava15()) {
        SSLContext sc;//from w ww  .  j a v  a2  s  . co  m
        sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { tm }, null);
        /* register with standard HTTP implementation */
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        /* register with Jakarta HTTPClient */
        Protocol https = new Protocol("https", new SSLSocketFactory(sc), 443);
        Protocol.registerProtocol("https", https);
    }
}

From source file:com.amalto.workbench.utils.SSLContextProvider.java

public synchronized static void buildContext(String algorithm, String keypath, String keypass, String keytype,
        String trustpath, String trustpass, String trusttype) {
    try {/*from ww  w . ja v  a  2s . c om*/
        KeyManager[] kms = buildKeyManagers(keypath, keypass, keytype);
        TrustManager[] tms = buildTrustManagers(trustpath, trustpass, trusttype);
        SSLContext sslcontext = SSLContext.getInstance(algorithm);
        sslcontext.init(kms, tms, null);
        context = sslcontext;
    } catch (Exception e) {
        throw new SecurityException(e.getMessage(), e);
    }
}

From source file:de.codecentric.jira.jenkins.plugin.servlet.RecentBuildsServlet.java

public RecentBuildsServlet(TemplateRenderer templateRenderer, JiraAuthenticationContext authenticationContext,
        PluginSettingsFactory settingsFactory, ApplicationProperties applicationProperties) {
    this.templateRenderer = templateRenderer;
    this.authenticationContext = authenticationContext;
    this.client = new HttpClient(new MultiThreadedHttpConnectionManager());
    this.serverList = new ServerList(settingsFactory);

    //test if jiraversion < 4.3
    IsPriorToJiraVersion isPrior = new IsPriorToJiraVersion(applicationProperties);
    isPrior.setmaxMajorVersion(4);/*w  w  w  . j  a va 2s .com*/
    isPrior.setmaxMinorVersion(3);
    this.old = isPrior.shouldDisplay(null);

    client.getParams().setAuthenticationPreemptive(true);

    //set SSLContext to accept all certificates
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SecureProtocolSocketFactory secureProtocolSocketFactory = new SSLProtocolSocketFactory();

    Protocol.registerProtocol("https",
            new Protocol("https", (ProtocolSocketFactory) secureProtocolSocketFactory, 443));

}

From source file:ee.ria.xroad.proxy.serverproxy.HttpClientCreator.java

private static SSLConnectionSocketFactory createSSLSocketFactory() throws Exception {
    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(createServiceKeyManager(), new TrustManager[] { new ServiceTrustManager() }, new SecureRandom());

    log.info("SSL context successfully created");

    return new CustomSSLSocketFactory(ctx, SystemProperties.getProxyClientTLSProtocols(),
            SystemProperties.getProxyClientTLSCipherSuites(), NoopHostnameVerifier.INSTANCE);
}