Example usage for javax.net.ssl TrustManagerFactory getTrustManagers

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

Introduction

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

Prototype

public final TrustManager[] getTrustManagers() 

Source Link

Document

Returns one trust manager for each type of trust material.

Usage

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/*w  w  w.j  a  v a  2  s . c o  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.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAnalyticsArtifactUploaderAdminServiceImpl.java

/**
 * Initializes the SSL Context/*from  ww  w . ja  va  2 s .c  om*/
 */
private void initSSLConnection()
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication
    sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
}

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

private void createKeystore() {
    try {/* w ww  .j  av a  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:de.metas.procurement.webui.ActiveMQBrokerConfiguration.java

/**
 * @return embedded ActiveMQ broker or <code>null</code>
 *///  w w  w.j  a  v a2  s .co m
@Bean
public BrokerService brokerService() throws Exception {
    if (!runEmbeddedBroker) {
        logger.info("Skip creating an ActiveMQ broker service");
        return null;
    }

    final BrokerService brokerService = new BrokerService();

    if (useSSL) {
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore keystore = KeyStore.getInstance("JKS");
            final Resource keyStoreResource = Application.getContext().getResource(keyStoreFileResourceURL);
            final InputStream keyStoreStream = keyStoreResource.getInputStream();
            keystore.load(keyStoreStream, keyStorePassword.toCharArray());

            kmf.init(keystore, keyStorePassword.toCharArray());
        }

        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore trustStore = KeyStore.getInstance("JKS");
            final Resource trustStoreResource = Application.getContext().getResource(trustStoreFileResourceURL);
            final InputStream trustStoreStream = trustStoreResource.getInputStream();
            trustStore.load(trustStoreStream, trustStorePassword.toCharArray());

            tmf.init(trustStore);
        }

        final SslContext sslContext = new SslContext(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        brokerService.setSslContext(sslContext);
    }

    //
    // "client" Connector
    {
        final TransportConnector connector = new TransportConnector();
        connector.setUri(new URI(brokerUrl.trim()));
        brokerService.addConnector(connector);
    }

    //
    // "Network of brokers" connector
    if (isSet(networkConnector_discoveryAddress)) {
        final DiscoveryNetworkConnector discoveryNetworkConnector = new DiscoveryNetworkConnector(
                new URI(networkConnector_discoveryAddress.trim()));
        discoveryNetworkConnector.setDuplex(true); // without this, we can send to the other broker, but won't get reposnses

        if (isSet(networkConnector_userName)) {
            discoveryNetworkConnector.setUserName(networkConnector_userName.trim());
        }
        if (isSet(networkConnector_password)) {
            discoveryNetworkConnector.setPassword(networkConnector_password.trim());
        }

        // we need to set ConduitSubscriptions to false,
        // see section "Conduit subscriptions and consumer selectors" on http://activemq.apache.org/networks-of-brokers.html
        discoveryNetworkConnector.setConduitSubscriptions(false);

        logger.info("Adding network connector: {}", networkConnector_discoveryAddress);
        brokerService.addNetworkConnector(discoveryNetworkConnector);
    }

    brokerService.setBrokerName(embeddedBrokerName);
    brokerService.start();
    logger.info("Embedded JMS broker started on URL " + brokerUrl);
    return brokerService;
}

From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Configure {@link SSLContext} and create EJB client properties.
 *
 * @param clientName/*w  ww.ja v  a2s.  c o  m*/
 * @return
 * @throws Exception
 */
private Properties configureEjbClient(String clientName) throws Exception {
    // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(
            KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()),
            KEYSTORE_PASSWORD.toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory
            .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray()));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);

    final Properties env = new Properties();
    env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
    env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST);
    env.put("jboss.naming.client.ejb.context", "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
    env.put(Context.SECURITY_PRINCIPAL, "admin");
    env.put(Context.SECURITY_CREDENTIALS, "testing");

    // SSL related config parameters
    env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
            "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
    return env;
}

From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java

/**
 * Returns a SSL Context. This is need for encryption, used by the
 * SSLSocketFactory./*from ww w. j  a  v a  2 s  . c  om*/
 * 
 * @return SSL Context
 * @throws ESCertificateException
 *             in case of failure retrieving the context
 */
public SSLContext getSSLContext() throws ESCertificateException {
    try {
        loadKeyStore();
        final KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        trustManagerFactory.init(keyStore);
        final SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$
        sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return sslContext;
    } catch (final NoSuchAlgorithmException e) {
        throw new ESCertificateException(Messages.KeyStoreManager_29, e);
    } catch (final UnrecoverableKeyException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    } catch (final KeyStoreException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    } catch (final KeyManagementException e) {
        throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$
    }
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

private X509TrustManager getX509TrustManager(final KeyStore trustStore)
        throws GeneralSecurityException, IOException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }//  w ww  . j  a  va2  s  .co m
    }
    return null;
}

From source file:org.wso2.carbon.extension.analytics.receiver.rabbitmq.internal.util.RabbitMQAdapterListener.java

public RabbitMQAdapterListener(RabbitMQBrokerConnectionConfiguration rabbitmqBrokerConnectionConfiguration,
        InputEventAdapterConfiguration eventAdapterConfiguration,
        InputEventAdapterListener inputEventAdapterListener) {

    connectionFactory = new ConnectionFactory();
    this.rabbitmqBrokerConnectionConfiguration = rabbitmqBrokerConnectionConfiguration;
    this.queueName = eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_QUEUE_NAME);
    this.exchangeName = eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_EXCHANGE_NAME);
    this.exchangeType = eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_EXCHANGE_TYPE);
    this.routeKey = eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_QUEUE_ROUTING_KEY);
    this.consumerTagString = eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.CONSUMER_TAG);
    this.adapterName = eventAdapterConfiguration.getName();
    this.eventAdapterListener = inputEventAdapterListener;
    this.tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    workerState = STATE_STOPPED;//from  ww  w  . j av a  2 s .  c  o  m
    STATE_STARTED = 1;
    if (routeKey == null) {
        routeKey = queueName;
    }
    if (!eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_ENABLED).equals("false")) {
        try {
            boolean sslEnabled = Boolean.parseBoolean(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_ENABLED));
            if (sslEnabled) {
                String keyStoreLocation = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_LOCATION);
                String keyStoreType = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_TYPE);
                String keyStorePassword = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_KEYSTORE_PASSWORD);
                String trustStoreLocation = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_LOCATION);
                String trustStoreType = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_TYPE);
                String trustStorePassword = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_TRUSTSTORE_PASSWORD);
                String sslVersion = eventAdapterConfiguration.getProperties()
                        .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_SSL_VERSION);

                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType)
                        || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation)
                        || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    log.debug("Truststore and keystore information is not provided");
                    if (StringUtils.isNotEmpty(sslVersion)) {
                        connectionFactory.useSslProtocol(sslVersion);
                    } else {
                        log.info("Proceeding with default SSL configuration");
                        connectionFactory.useSslProtocol();
                    }
                } else {
                    char[] keyPassphrase = keyStorePassword.toCharArray();
                    KeyStore ks = KeyStore.getInstance(keyStoreType);
                    ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, keyPassphrase);

                    char[] trustPassphrase = trustStorePassword.toCharArray();
                    KeyStore tks = KeyStore.getInstance(trustStoreType);
                    tks.load(new FileInputStream(trustStoreLocation), trustPassphrase);

                    TrustManagerFactory tmf = TrustManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    tmf.init(tks);

                    SSLContext c = SSLContext.getInstance(sslVersion);
                    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                    connectionFactory.useSslProtocol(c);
                }
            }
        } catch (IOException e) {
            handleException("TrustStore or KeyStore File path is incorrect. Specify KeyStore location or "
                    + "TrustStore location Correctly.", e);
        } catch (CertificateException e) {
            handleException("TrustStore or keyStore is not specified. So Security certificate"
                    + " Exception happened.  ", e);
        } catch (NoSuchAlgorithmException e) {
            handleException("Algorithm is not available in KeyManagerFactory class.", e);
        } catch (UnrecoverableKeyException e) {
            handleException("Unable to recover Key", e);
        } catch (KeyStoreException e) {
            handleException("Error in KeyStore or TrustStore Type", e);
        } catch (KeyManagementException e) {
            handleException("Error in Key Management", e);
        }
    }

    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_FACTORY_HEARTBEAT))) {
        try {
            int heartbeatValue = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQEventAdapterConstants.RABBITMQ_FACTORY_HEARTBEAT));
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    connectionFactory.setHost(rabbitmqBrokerConnectionConfiguration.getHostName());
    try {
        int port = Integer.parseInt(rabbitmqBrokerConnectionConfiguration.getPort());
        if (port > 0) {
            connectionFactory.setPort(port);
        }
    } catch (NumberFormatException e) {
        handleException("Number format error in port number", e);
    }
    connectionFactory.setUsername(rabbitmqBrokerConnectionConfiguration.getUsername());
    connectionFactory.setPassword(rabbitmqBrokerConnectionConfiguration.getPassword());
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST))) {
        connectionFactory.setVirtualHost(eventAdapterConfiguration.getProperties()
                .get(RabbitMQEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST));
    }
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_COUNT))) {
        try {
            retryCountMax = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_COUNT));
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
        }
    }
    if (!StringUtils.isEmpty(eventAdapterConfiguration.getProperties()
            .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_INTERVAL))) {
        try {
            retryInterval = Integer.parseInt(eventAdapterConfiguration.getProperties()
                    .get(RabbitMQEventAdapterConstants.RABBITMQ_CONNECTION_RETRY_INTERVAL));
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading retry interval value. Proceeding with default value (30000ms)",
                    e);
        }
    }
}

From source file:de.betterform.connector.http.ssl.BetterFORMTrustManager.java

private TrustManager[] getCustomX509TrustManagers(final URL url, final String password)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    if (url == null) {
        throw new IllegalArgumentException("BetterFORMTrustManager: Keystore url may not be null");
    }// www . j a va  2  s  .c om

    LOGGER.debug("BetterFORMTrustManager: initializing custom key store");
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = null;
    try {
        is = url.openStream();
        customKeystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }

    trustManagerFactory.init(customKeystore);

    TrustManager[] customX509TrustManagers = trustManagerFactory.getTrustManagers();
    for (int i = 0; i < customX509TrustManagers.length; i++) {
        if (customX509TrustManagers[i] instanceof X509TrustManager) {
            customX509TrustManagers[i] = new AuthSSLX509TrustManager(
                    (X509TrustManager) customX509TrustManagers[i]);
        }
    }
    return customX509TrustManagers;
}