Example usage for javax.net.ssl TrustManagerFactory getInstance

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

Introduction

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

Prototype

public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a TrustManagerFactory object that acts as a factory for trust managers.

Usage

From source file:it.greenvulcano.gvesb.http.ssl.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  2  s  .c om*/
    logger.debug("createTrustManagers - Initializing trust manager: " + keystore.aliases().nextElement());
    logger.debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:org.apache.jmeter.util.JsseSSLManager.java

private SSLContext createContext() throws GeneralSecurityException {
    SSLContext context;/*w ww.  j a  v a2  s.c  o  m*/
    if (pro != null) {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, pro); // $NON-NLS-1$
    } else {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL); // $NON-NLS-1$
    }
    KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    JmeterKeyStore keys = this.getKeyStore();
    managerFactory.init(null, defaultpw == null ? new char[] {} : defaultpw.toCharArray());
    KeyManager[] managers = managerFactory.getKeyManagers();
    KeyManager[] newManagers = new KeyManager[managers.length];

    log.debug(keys.getClass().toString());

    // Now wrap the default managers with our key manager
    for (int i = 0; i < managers.length; i++) {
        if (managers[i] instanceof X509KeyManager) {
            X509KeyManager manager = (X509KeyManager) managers[i];
            newManagers[i] = new WrappedX509KeyManager(manager, keys);
        } else {
            newManagers[i] = managers[i];
        }
    }

    // Get the default trust managers
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(this.getTrustStore());

    // Wrap the defaults in our custom trust manager
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new CustomX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    context.init(newManagers, trustmanagers, this.rand);
    if (log.isDebugEnabled()) {
        String[] dCiphers = context.getSocketFactory().getDefaultCipherSuites();
        String[] sCiphers = context.getSocketFactory().getSupportedCipherSuites();
        int len = (dCiphers.length > sCiphers.length) ? dCiphers.length : sCiphers.length;
        for (int i = 0; i < len; i++) {
            if (i < dCiphers.length) {
                log.debug("Default Cipher: " + dCiphers[i]);
            }
            if (i < sCiphers.length) {
                log.debug("Supported Cipher: " + sCiphers[i]);
            }
        }
    }
    return context;
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null)
        throw new IllegalArgumentException("Keystore may not be null");

    Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);//from w  w w  .j  av a 2s  .c om
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:org.apache.ambari.server.controller.internal.URLStreamProvider.java

protected HttpsURLConnection getSSLConnection(String spec) throws IOException {

    if (sslSocketFactory == null) {
        synchronized (this) {
            if (sslSocketFactory == null) {
                try {
                    FileInputStream in = new FileInputStream(new File(path));
                    KeyStore store = KeyStore.getInstance(type == null ? KeyStore.getDefaultType() : type);

                    store.load(in, password.toCharArray());
                    in.close();/*from w  ww.  j  a  v  a  2s. c om*/

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

                    tmf.init(store);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(null, tmf.getTrustManagers(), null);

                    sslSocketFactory = context.getSocketFactory();
                } catch (Exception e) {
                    throw new IOException("Can't get connection.", e);
                }
            }
        }
    }
    HttpsURLConnection connection = (HttpsURLConnection) (new URL(spec).openConnection());

    connection.setSSLSocketFactory(sslSocketFactory);

    return connection;
}

From source file:com.sonatype.nexus.ssl.plugin.internal.TrustStoreImpl.java

private static TrustManager[] getSystemTrustManagers() throws Exception {
    TrustManagerFactory trustManagerFactory;

    String trustAlgorithm = System.getProperty("ssl.TrustManagerFactory.algorithm");
    if (trustAlgorithm == null) {
        trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    }/* ww w.ja v  a  2  s  .  com*/
    String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
    if (trustStoreType == null) {
        trustStoreType = KeyStore.getDefaultType();
    }
    if ("none".equalsIgnoreCase(trustStoreType)) {
        trustManagerFactory = TrustManagerFactory.getInstance(trustAlgorithm);
    } else {
        File trustStoreFile;
        KeyStore trustStore;

        String trustStoreFileName = System.getProperty("javax.net.ssl.trustStore");
        if (trustStoreFileName != null) {
            trustStoreFile = new File(trustStoreFileName);
            trustManagerFactory = TrustManagerFactory.getInstance(trustAlgorithm);
            final String trustStoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider");
            if (trustStoreProvider != null) {
                trustStore = KeyStore.getInstance(trustStoreType, trustStoreProvider);
            } else {
                trustStore = KeyStore.getInstance(trustStoreType);
            }
        } else {
            File javaHome = new File(System.getProperty("java.home"));
            File file = new File(javaHome, "lib/security/jssecacerts");
            if (!file.exists()) {
                file = new File(javaHome, "lib/security/cacerts");
                trustStoreFile = file;
            } else {
                trustStoreFile = file;
            }

            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        }
        final String password = System.getProperty("javax.net.ssl.trustStorePassword");
        try (FileInputStream in = new FileInputStream(trustStoreFile)) {
            trustStore.load(in, password != null ? password.toCharArray() : null);
        }
        trustManagerFactory.init(trustStore);
    }
    return trustManagerFactory.getTrustManagers();
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

/**
 * {@inheritDoc}/*from   w w w  .  jav a  2s.c o m*/
 */
@Override
public TrustManager[] createTrustManagers() {
    KeyInfoManager keyInfoManager = null;

    try {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(getKeyStoreParameters(), keyInfoManager);

        logger.debug("Initializing trust managers");
        TrustManagerFactory tmfactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmfactory.init(ks);
        return tmfactory.getTrustManagers();
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Unable to create key manager", e);
    } finally {
        if (keyInfoManager != null) {
            keyInfoManager.clear();
        }
    }
}

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Loads the trusted certificate authorities according to the specified properties.
 *
 * @param properties properties/*from  ww w. j a  va2s  .co  m*/
 * @return map of certificate authorities
 */
private Map<String, X509Certificate> getTrustedCAs(final NiFiProperties properties) {
    final Map<String, X509Certificate> certificateAuthorities = new HashMap<>();

    // get the path to the truststore
    final String truststorePath = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
    if (truststorePath == null) {
        throw new IllegalArgumentException("The truststore path is required.");
    }

    // get the truststore password
    final char[] truststorePassword;
    final String rawTruststorePassword = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
    if (rawTruststorePassword == null) {
        truststorePassword = new char[0];
    } else {
        truststorePassword = rawTruststorePassword.toCharArray();
    }

    // load the configured truststore
    try (final FileInputStream fis = new FileInputStream(truststorePath)) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(KeyStore.getDefaultType());
        truststore.load(fis, truststorePassword);

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

        // consider any certificates in the truststore as a trusted ca
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                for (X509Certificate ca : ((X509TrustManager) trustManager).getAcceptedIssuers()) {
                    certificateAuthorities.put(ca.getSubjectX500Principal().getName(), ca);
                }
            }
        }
    } catch (final Exception e) {
        throw new IllegalStateException("Unable to load the configured truststore: " + e);
    }

    return certificateAuthorities;
}

From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java

private void doConnect(final StudioProgressMonitor monitor) throws Exception {
    ldapConnection = null;//  w  w  w  .j a  v  a 2s .  c om
    isConnected = true;

    ldapConnectionConfig = new LdapConnectionConfig();
    ldapConnectionConfig.setLdapHost(connection.getHost());
    ldapConnectionConfig.setLdapPort(connection.getPort());

    long timeout = connection.getTimeout();

    if (timeout < 0) {
        timeout = 30000L;
    }

    ldapConnectionConfig.setTimeout(timeout);

    binaryAttributeDetector = new DefaultConfigurableBinaryAttributeDetector();
    ldapConnectionConfig.setBinaryAttributeDetector(binaryAttributeDetector);

    if ((connection.getEncryptionMethod() == EncryptionMethod.LDAPS)
            || (connection.getEncryptionMethod() == EncryptionMethod.START_TLS)) {
        ldapConnectionConfig.setUseSsl(connection.getEncryptionMethod() == EncryptionMethod.LDAPS);
        ldapConnectionConfig.setUseTls(connection.getEncryptionMethod() == EncryptionMethod.START_TLS);

        try {
            // get default trust managers (using JVM "cacerts" key store)
            TrustManagerFactory factory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init((KeyStore) null);
            TrustManager[] defaultTrustManagers = factory.getTrustManagers();

            // create wrappers around the trust managers
            StudioTrustManager[] trustManagers = new StudioTrustManager[defaultTrustManagers.length];

            for (int i = 0; i < defaultTrustManagers.length; i++) {
                trustManagers[i] = new StudioTrustManager((X509TrustManager) defaultTrustManagers[i]);
                trustManagers[i].setHost(connection.getHost());
            }

            ldapConnectionConfig.setTrustManagers(trustManagers);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                // Set lower timeout for connecting
                long oldTimeout = ldapConnectionConfig.getTimeout();
                ldapConnectionConfig.setTimeout(Math.min(oldTimeout, 5000L));

                // Connecting
                ldapConnection = new LdapNetworkConnection(ldapConnectionConfig);
                boolean connected = ldapConnection.connect();

                if (!connected) {
                    throw new Exception(Messages.DirectoryApiConnectionWrapper_UnableToConnect);
                }

                // Set old timeout again
                ldapConnectionConfig.setTimeout(oldTimeout);
            } catch (Exception e) {
                exception = e;

                try {
                    if (ldapConnection != null) {
                        ldapConnection.close();
                    }
                } catch (Exception exception) {
                    // Nothing to do
                } finally {
                    ldapConnection = null;
                    binaryAttributeDetector = null;
                }
            }
        }
    };

    runAndMonitor(runnable, monitor);

    if (runnable.getException() != null) {
        throw runnable.getException();
    }
}

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);/*from   w  w w.j  av  a 2  s. c  om*/

    final KeyManager[] keyManagers;
    if (keystore == null) {
        keyManagers = null;
    } 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.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClientConnectionManager createConnectionManager() {
    PoolingHttpClientConnectionManager manager;
    if ("https".equals(graphiteScheme) && !StringUtils.isEmpty(graphiteKeyStore)
            && !StringUtils.isEmpty(graphiteKeyStorePassword) && !StringUtils.isEmpty(graphiteTrustStore)) {
        try {//www. j ava  2s .  c o m
            KeyStore keyStore = loadKeyStore(graphiteKeyStore, graphiteKeyStorePassword);
            KeyStore trustStore = loadKeyStore(graphiteTrustStore, null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, graphiteKeyStorePassword.toCharArray());
            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(keyManagers, trustManagers, null);

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("https", sslsf).build();

            manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (Exception e) {
            LOGGER.warn("A problem occurred when building SSLConnectionSocketFactory", e);
            throw new RuntimeException("Error while building SSLConnectionSocketFactory", e);
        }
    } else {
        manager = new PoolingHttpClientConnectionManager();
    }

    manager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    return manager;
}