Example usage for javax.net.ssl TrustManagerFactory getDefaultAlgorithm

List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory getDefaultAlgorithm.

Prototype

public static final String getDefaultAlgorithm() 

Source Link

Document

Obtains the default TrustManagerFactory algorithm name.

Usage

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

public static SSLSocketFactory setupSSLSocketFactory(Context context, PrivateKey privateKey,
        X509Certificate certificate, boolean acceptAnyCertificate)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException, NoSuchProviderException {

    // in-memory keystore
    KeyManager[] km = null;//from w w  w.  j av a 2 s  .  c  o m
    if (privateKey != null && certificate != null) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(null, null);
        keystore.setKeyEntry("private", privateKey, null, new Certificate[] { certificate });

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

    // trust managers
    TrustManager[] tm;

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

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

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        } };
    } else {
        // load merged truststore (system + internal)
        KeyStore trustStore = InternalTrustStore.getTrustStore(context);

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

        tm = tmFactory.getTrustManagers();
    }

    SSLContext ctx = SSLContext.getInstance("TLSv1");
    ctx.init(km, tm, null);
    return new TlsOnlySocketFactory(ctx.getSocketFactory(), true);
}

From source file:org.apache.nifi.elasticsearch.ElasticSearchClientServiceImpl.java

private SSLContext buildSslContext(SSLContextService sslService) throws IOException, CertificateException,
        NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance(sslService.getKeyStoreType());
    KeyStore trustStore = KeyStore.getInstance("JKS");

    try (final InputStream is = new FileInputStream(sslService.getKeyStoreFile())) {
        keyStore.load(is, sslService.getKeyStorePassword().toCharArray());
    }// w w w.jav  a  2s. com

    try (final InputStream is = new FileInputStream(sslService.getTrustStoreFile())) {
        trustStore.load(is, sslService.getTrustStorePassword().toCharArray());
    }

    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, sslService.getKeyStorePassword().toCharArray());
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    SSLContext context1 = SSLContext.getInstance(sslService.getSslAlgorithm());
    context1.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return context1;
}

From source file:com.budrotech.jukebox.service.ssl.SSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keyStorePassword, final SecureRandom random, final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;//from w  w w.  j  a v a  2s  . c o  m
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keystore);

    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    if (trustManagers != null && trustStrategy != null) {
        for (int i = 0; i < trustManagers.length; i++) {
            TrustManager tm = trustManagers[i];

            if (tm instanceof X509TrustManager) {
                trustManagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
            }
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keyManagers, trustManagers, random);

    return sslcontext;
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSSLListener.java

/**
 * Create the SSLContext to be used by this listener
 * @param transportIn the Axis2 transport description
 * @return the SSLContext to be used/*from w  w  w .  j ava2  s.c om*/
 */
protected SSLContext getSSLContext(TransportInDescription transportIn) throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    Parameter keyParam = transportIn.getParameter("keystore");
    Parameter trustParam = transportIn.getParameter("truststore");

    if (keyParam != null) {
        OMElement ksEle = keyParam.getParameterElement().getFirstElement();
        String location = ksEle.getFirstChildWithName(new QName("Location")).getText();
        String type = ksEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Identity Keystore from : " + location);

            keyStore.load(fis, storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustParam != null) {
        OMElement tsEle = trustParam.getParameterElement().getFirstElement();
        String location = tsEle.getFirstChildWithName(new QName("Location")).getText();
        String type = tsEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText();

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Trust Keystore from : " + location);

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

    } catch (GeneralSecurityException gse) {
        log.error("Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

From source file:org.apache.camel.component.file.remote.FtpsEndpoint.java

/**
 * Create the FTPS client.//  w  w w .  j a  v  a2  s  .  co m
 */
protected FTPClient createFtpClient() throws Exception {
    FTPSClient client = null;

    if (sslContextParameters != null) {
        SSLContext context = sslContextParameters.createSSLContext();

        client = new FTPSClient(getFtpsConfiguration().isImplicit(), context);

        // The FTPSClient tries to manage the following SSLSocket related configuration options
        // on its own based on internal configuration options.  FTPSClient does not lend itself
        // to subclassing for the purpose of overriding this behavior (private methods, fields, etc.).
        // As such, we create a socket (preconfigured by SSLContextParameters) from the context
        // we gave to FTPSClient and then setup FTPSClient to reuse the already configured configuration
        // from the socket for all future sockets it creates.  Not sexy and a little brittle, but it works.
        SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket();
        client.setEnabledCipherSuites(socket.getEnabledCipherSuites());
        client.setEnabledProtocols(socket.getEnabledProtocols());
        client.setNeedClientAuth(socket.getNeedClientAuth());
        client.setWantClientAuth(socket.getWantClientAuth());
        client.setEnabledSessionCreation(socket.getEnableSessionCreation());
    } else {
        client = new FTPSClient(getFtpsConfiguration().getSecurityProtocol(),
                getFtpsConfiguration().isImplicit());

        if (ftpClientKeyStoreParameters != null) {
            String type = (ftpClientKeyStoreParameters.containsKey("type"))
                    ? (String) ftpClientKeyStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientKeyStoreParameters.get("file");
            String password = (String) ftpClientKeyStoreParameters.get("password");
            String algorithm = (ftpClientKeyStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientKeyStoreParameters.get("algorithm")
                    : KeyManagerFactory.getDefaultAlgorithm();
            String keyPassword = (String) ftpClientKeyStoreParameters.get("keyPassword");

            KeyStore keyStore = KeyStore.getInstance(type);
            FileInputStream keyStoreFileInputStream = new FileInputStream(new File(file));
            try {
                keyStore.load(keyStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(keyStoreFileInputStream, "keyStore", log);
            }

            KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(algorithm);
            keyMgrFactory.init(keyStore, keyPassword.toCharArray());
            client.setNeedClientAuth(true);
            client.setKeyManager(keyMgrFactory.getKeyManagers()[0]);
        }

        if (ftpClientTrustStoreParameters != null) {
            String type = (ftpClientTrustStoreParameters.containsKey("type"))
                    ? (String) ftpClientTrustStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientTrustStoreParameters.get("file");
            String password = (String) ftpClientTrustStoreParameters.get("password");
            String algorithm = (ftpClientTrustStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientTrustStoreParameters.get("algorithm")
                    : TrustManagerFactory.getDefaultAlgorithm();

            KeyStore trustStore = KeyStore.getInstance(type);
            FileInputStream trustStoreFileInputStream = new FileInputStream(new File(file));
            try {
                trustStore.load(trustStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(trustStoreFileInputStream, "trustStore", log);
            }

            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(algorithm);
            trustMgrFactory.init(trustStore);

            client.setTrustManager(trustMgrFactory.getTrustManagers()[0]);
        }
    }

    return client;
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

private TrustManagerFactory initTrustManagerFactory(String trustStoreType, String trustStoreLocation,
        String trustStorePasswordPath) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, SecurityException {
    TrustManagerFactory tmf;/*w w  w  .  ja v  a2  s .  c  o m*/

    if (Strings.isNullOrEmpty(trustStoreLocation)) {
        LOG.error("Trust Store location cannot be empty!");
        throw new SecurityException("Trust Store location cannot be empty!");
    }

    String trustStorePassword = "";
    if (!Strings.isNullOrEmpty(trustStorePasswordPath)) {
        trustStorePassword = getPasswordFromFile(trustStorePasswordPath);
    }

    // Initialize trust file
    KeyStore ts = loadKeyStore(trustStoreType, trustStoreLocation, trustStorePassword);
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);

    return tmf;
}

From source file:com.ubergeek42.WeechatAndroid.service.RelayService.java

private void createKeystore() {
    try {//from   w w  w .java 2 s.  c  o m
        sslKeystore.load(null, null);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        // Copy current certs into our keystore so we can use it...
        // TODO: don't actually do this...
        X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
        for (X509Certificate cert : xtm.getAcceptedIssuers()) {
            sslKeystore.setCertificateEntry(cert.getSubjectDN().getName(), cert);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    saveKeystore();
}

From source file:io.dropwizard.revolver.http.RevolverHttpClientFactory.java

private static SSLContext getSSLContext(final String keyStorePath, final String keyStorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {
    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream instream = RevolverHttpClientFactory.class.getClassLoader()
            .getResourceAsStream(keyStorePath)) {
        keyStore.load(instream, keyStorePassword.toCharArray());
    }/*w  ww .ja va2  s .  c  om*/
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

@Override
protected void configureClient() {

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout());
    requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout());
    requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled());

    RequestConfig requestConfig = requestBuilder.build();

    boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath())
            && StringUtils.isNotEmpty(metadata.getKeyStorePassword());

    boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath())
            && StringUtils.isNotEmpty(metadata.getTrustStorePassword());

    autoCloseable = metadata.isAutoCloseable();

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    SSLContext sslContext = null;

    try {//from www.j a  va  2s.c  o  m

        String keystoreType = "JKS";
        if (addSslSupport && addTrustSupport) {

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray())
                    .loadTrustMaterial(trustStore, null).build();

        } else if (addSslSupport) {

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore keyStore = KeyStore.getInstance(keystoreType);
            keyStore.load(new FileInputStream(metadata.getKeyStorePath()),
                    metadata.getKeyStorePassword().toCharArray());

            tmf.init(keyStore);

            sslContext = SSLContexts.custom().useProtocol("SSL")
                    .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build();

            sslContext.init(null, tmf.getTrustManagers(), null);

            SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

            httpClientBuilder.setSSLSocketFactory(sf);

        } else if (addTrustSupport) {

            KeyStore trustStore = KeyStore.getInstance(keystoreType);
            trustStore.load(new FileInputStream(metadata.getTrustStorePath()),
                    metadata.getTrustStorePassword().toCharArray());

            sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build();

        }

        if (addSslSupport | addTrustSupport) {
            SSLContext.setDefault(sslContext);
            httpClientBuilder.setSslcontext(sslContext);
        }

    } catch (Exception e) {
        LOGGER.error("can't set TLS Support. Error is: {}", e, e);
    }

    httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig)
            .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS)
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()));

    HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom();

    httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig)
            .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress())
            .setMaxConnTotal(metadata.getMaxConnectionsTotal())
            .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout()))
            .setSSLContext(sslContext);

    if (metadata.isDisableCookies()) {
        httpClientBuilder.disableCookieManagement();
        httpAsyncClientBuilder.disableCookieManagement();
    }

    if (hostnameVerifier != null) {
        httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
        httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier);
    }

    if (!followRedirects) {
        httpClientBuilder.disableRedirectHandling();
    }

    httpClient = httpClientBuilder.build();

    httpAsyncClient = httpAsyncClientBuilder.build();

    httpAsyncClient.start();

}

From source file:org.springframework.vault.config.ClientHttpRequestFactoryFactory.java

private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword)
        throws GeneralSecurityException, IOException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    loadKeyStore(trustFile, storePassword, trustStore);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return trustManagerFactory;
}