Example usage for javax.net.ssl TrustManagerFactory init

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

Introduction

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

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:gov.nist.toolkit.soap.axis2.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//from w  w  w.ja v  a 2s  .c  om
    LOG.debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();

    LOG.debug("Found " + trustmanagers.length + " trust managers");

    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        } else {
            System.out.println("non 509 trust manager: class is " + trustmanagers[i].getClass().getName());
        }
    }
    return trustmanagers;
}

From source file:org.signserver.client.cli.defaultimpl.KeyStoreOptions.java

private static void setDefaultSocketFactory(final KeyStore truststore, final KeyStore keystore, String keyAlias,
        char[] keystorePassword)
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(truststore);

    final KeyManager[] keyManagers;
    if (keystore == null) {
        keyManagers = null;/*  w  ww.ja  va 2s.c  o  m*/
    } else {
        if (keyAlias == null) {
            keyAlias = keystore.aliases().nextElement();
        }
        final KeyManagerFactory kKeyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        kKeyManagerFactory.init(keystore, keystorePassword);
        keyManagers = kKeyManagerFactory.getKeyManagers();
        for (int i = 0; i < keyManagers.length; i++) {
            if (keyManagers[i] instanceof X509KeyManager) {
                keyManagers[i] = new AliasKeyManager((X509KeyManager) keyManagers[i], keyAlias);
            }
        }
    }

    final SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagers, tmf.getTrustManagers(), new SecureRandom());

    SSLSocketFactory factory = context.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(factory);
}

From source file:com.netflix.discovery.shared.EurekaJerseyClient.java

private static TrustManager[] createTrustManagers(KeyStore trustStore) {
    TrustManagerFactory factory = null;
    try {//from  w ww .java2s. c om
        factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init(trustStore);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    final TrustManager[] managers = factory.getTrustManagers();

    return managers;

}

From source file:com.vmware.identity.openidconnect.client.TestUtils.java

static IdmClient createIdmClient(AccessToken accessToken, String domainControllerFQDN, int domainControllerPort,
        KeyStore keyStore) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    idmClient.setToken(restAccessToken);
    return idmClient;
}

From source file:com.vmware.identity.openidconnect.client.TestUtils.java

static VmdirClient createVMdirClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort, KeyStore keyStore) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    VmdirClient vmdirClient = new VmdirClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    vmdirClient.setToken(restAccessToken);
    return vmdirClient;
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//ww  w  . ja  va  2 s  .c  o m
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    return trustmanagers;
}

From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception {
    final URL url2 = new URL(url);
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(),
            url2.getPort() > 0 ? url2.getPort() : 443);
    socket.setSoTimeout(10000);// w  w w. j a  va  2 s  .c  o m
    try {
        socket.startHandshake();
        socket.close();
    } catch (SSLException e) {
    }

    final X509Certificate[] chain = trustManager.chain;
    if (chain == null) {
        LOGGER.error("Could not obtain server certificate chain from: " + url);
        return;
    }

    final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    final MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate cert = chain[i];
        final String alias = url2.getHost() + "-" + (i + 1);
        if (!trustStore.containsAlias(alias)) {
            sha1.update(cert.getEncoded());
            md5.update(cert.getEncoded());
            LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN()
                    + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: "
                    + printHexBinary(md5.digest()) + ", Alias: " + alias);
            trustStore.setCertificateEntry(alias, cert);
        }
    }
}

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

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

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

    try (InputStream inputStream = trustFile.getInputStream()) {
        trustStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
    }//from   w  w  w.j  a va 2  s  .  c om

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

    return trustManagerFactory;
}

From source file:it.paolorendano.clm.AbstractCassandraDAO.java

/**
 * Gets the SSL context./*from   www.j a  v  a  2s .  c om*/
 *
 * @param truststorePath the truststore path
 * @param truststorePassword the truststore password
 * @param keystorePath the keystore path
 * @param keystorePassword the keystore password
 * @return the SSL context
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws KeyStoreException the key store exception
 * @throws CertificateException the certificate exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws UnrecoverableKeyException the unrecoverable key exception
 * @throws KeyManagementException the key management exception
 */
private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath,
        String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    /* taken from http://www.datastax.com/dev/blog/accessing-secure-dse-clusters-with-cql-native-protocol */

    FileInputStream tsf = new FileInputStream(truststorePath);
    FileInputStream ksf = new FileInputStream(keystorePath);
    SSLContext ctx = SSLContext.getInstance("SSL");

    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(tsf, truststorePassword.toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(ksf, keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keystorePassword.toCharArray());

    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return ctx;
}

From source file:org.lealone.cluster.security.SSLFactory.java

public static SSLContext createSSLContext(EncryptionOptions options, boolean buildTruststore)
        throws IOException {
    FileInputStream tsf = null;/*w ww . ja va 2  s  .co  m*/
    FileInputStream ksf = null;
    SSLContext ctx;
    try {
        ctx = SSLContext.getInstance(options.protocol);
        TrustManager[] trustManagers = null;

        if (buildTruststore) {
            tsf = new FileInputStream(options.truststore);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(options.algorithm);
            KeyStore ts = KeyStore.getInstance(options.store_type);
            ts.load(tsf, options.truststore_password.toCharArray());
            tmf.init(ts);
            trustManagers = tmf.getTrustManagers();
        }

        ksf = new FileInputStream(options.keystore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(options.algorithm);
        KeyStore ks = KeyStore.getInstance(options.store_type);
        ks.load(ksf, options.keystore_password.toCharArray());
        if (!checkedExpiry) {
            for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
                String alias = aliases.nextElement();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    Date expires = ((X509Certificate) ks.getCertificate(alias)).getNotAfter();
                    if (expires.before(new Date()))
                        logger.warn("Certificate for {} expired on {}", alias, expires);
                }
            }
            checkedExpiry = true;
        }
        kmf.init(ks, options.keystore_password.toCharArray());

        ctx.init(kmf.getKeyManagers(), trustManagers, null);

    } catch (Exception e) {
        throw new IOException("Error creating the initializing the SSL Context", e);
    } finally {
        FileUtils.closeQuietly(tsf);
        FileUtils.closeQuietly(ksf);
    }
    return ctx;
}