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:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java

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

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

        return sslContext;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (UnrecoverableKeyException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyStoreException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyManagementException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    }
}

From source file:org.apache.synapse.transport.nhttp.config.ClientConnFactoryBuilder.java

private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert)
        throws AxisFault {

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

    if (keyStoreElt != null) {
        String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {/* w w w.jav a 2 s.c  o m*/
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.info(name + " 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(name + " Error loading Keystore : " + location, gse);
            throw new AxisFault("Error loading Keystore : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Keystore : " + location, ioe);
            throw new AxisFault("Error opening Keystore : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreElt != null) {
        if (novalidatecert && log.isWarnEnabled()) {
            log.warn(name + " Ignoring novalidatecert parameter since a truststore has been specified");
        }

        String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText();

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.info(name + " 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(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " 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) {
                }
            }
        }
    } else if (novalidatecert) {
        if (log.isWarnEnabled()) {
            log.warn(name + " Server certificate validation (trust) has been disabled. "
                    + "DO NOT USE IN PRODUCTION!");
        }
        trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
    }

    try {
        final Parameter sslpParameter = transportOut.getParameter("SSLProtocol");
        final String sslProtocol = sslpParameter != null ? sslpParameter.getValue().toString() : "TLS";
        SSLContext sslcontext = SSLContext.getInstance(sslProtocol);
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

    } catch (GeneralSecurityException gse) {
        log.error(name + " 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.mule.api.security.tls.TlsConfiguration.java

private void initTrustManagerFactory() throws CreateException {
    if (null != trustStoreName) {
        trustStorePassword = null == trustStorePassword ? "" : trustStorePassword;

        KeyStore trustStore;// ww  w .  jav  a2s .co  m
        try {
            trustStore = KeyStore.getInstance(trustStoreType);
            InputStream is = IOUtils.getResourceAsStream(trustStoreName, getClass());
            if (null == is) {
                throw new FileNotFoundException(
                        "Failed to load truststore from classpath or local file: " + trustStoreName);
            }
            trustStore.load(is, trustStorePassword.toCharArray());
        } catch (Exception e) {
            throw new CreateException(CoreMessages.failedToLoad("TrustStore: " + trustStoreName), e, this);
        }

        try {
            trustManagerFactory = TrustManagerFactory.getInstance(trustManagerAlgorithm);
            trustManagerFactory.init(trustStore);
        } catch (Exception e) {
            throw new CreateException(
                    CoreMessages.failedToLoad("Trust Manager (" + trustManagerAlgorithm + ")"), e, this);
        }
    }
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

private HttpsURLConnection openSecureConnection(URL url) throws Exception {

    InputStream keyStream = new FileInputStream(truststorePath);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(keyStream, Optional.ofNullable(truststorePassword).orElse("").toCharArray());

    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
            Optional.ofNullable(truststoreAlgorithm).orElseGet(TrustManagerFactory::getDefaultAlgorithm));
    trustFactory.init(keystore);/*from   w ww  . j  a  v  a2 s.c  o m*/

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

    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();

    httpsURLConnection.setSSLSocketFactory(context.getSocketFactory());

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

    return httpsURLConnection;
}

From source file:org.wildfly.test.integration.elytron.sasl.mgmt.AbstractKerberosMgmtSaslTestBase.java

/**
 * Get the trust manager for {@link #CLIENT_TRUSTSTORE_FILE}.
 *
 * @return the trust manager/*from   ww  w.  j av  a 2 s. c  o  m*/
 */
protected static X509TrustManager getTrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(loadKeyStore(CLIENT_TRUSTSTORE_FILE));

    for (TrustManager current : trustManagerFactory.getTrustManagers()) {
        if (current instanceof X509TrustManager) {
            return (X509TrustManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509TrustManager.");
}

From source file:org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.java

private Tuple<SSLSocketFactory, X509TrustManager> createSslSocketFactory(final NiFiProperties properties) {
    final SSLContext sslContext = SslContextFactory.createSslContext(properties);

    if (sslContext == null) {
        return null;
    }/*  w  w  w  .  j  a v a  2  s .c om*/

    try {
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");

        // initialize the KeyManager array to null and we will overwrite later if a keystore is loaded
        KeyManager[] keyManagers = null;

        // we will only initialize the keystore if properties have been supplied by the SSLContextService
        final String keystoreLocation = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE);
        final String keystorePass = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
        final String keystoreType = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);

        // prepare the keystore
        final KeyStore keyStore = KeyStore.getInstance(keystoreType);

        try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
            keyStore.load(keyStoreStream, keystorePass.toCharArray());
        }

        keyManagerFactory.init(keyStore, keystorePass.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();

        // we will only initialize the truststure if properties have been supplied by the SSLContextService
        // load truststore
        final String truststoreLocation = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
        final String truststorePass = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
        final String truststoreType = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);

        KeyStore truststore = KeyStore.getInstance(truststoreType);
        truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
        trustManagerFactory.init(truststore);

        // TrustManagerFactory.getTrustManagers returns a trust manager for each type of trust material. Since we are getting a trust manager factory that uses "X509"
        // as it's trust management algorithm, we are able to grab the first (and thus the most preferred) and use it as our x509 Trust Manager
        //
        // https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/TrustManagerFactory.html#getTrustManagers--
        final X509TrustManager x509TrustManager;
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers[0] != null) {
            x509TrustManager = (X509TrustManager) trustManagers[0];
        } else {
            throw new IllegalStateException("List of trust managers is null");
        }

        // if keystore properties were not supplied, the keyManagers array will be null
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);

        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        return new Tuple<>(sslSocketFactory, x509TrustManager);
    } catch (final Exception e) {
        throw new RuntimeException(
                "Failed to create SSL Socket Factory for replicating requests across the cluster");
    }
}

From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java

private void configureHttps(WebClient client) {
    LOGGER.debug("Configuring client for HTTPS");
    HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit();
    if (null != conduit) {
        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
        }/*w  w w  .j a v a  2  s  .co  m*/

        params.setDisableCNCheck(true);

        KeyStore keyStore;
        KeyStore trustStore;
        FileInputStream tsFIS = null;
        FileInputStream ksFIS = null;
        try {
            String trustStorePath = System.getProperty("javax.net.ssl.trustStore");
            String trustStoreType = System.getProperty("javax.net.ssl.trustStoreType");
            String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");

            trustStore = KeyStore.getInstance(trustStoreType);
            File trustStoreFile = new File(trustStorePath);
            tsFIS = new FileInputStream(trustStoreFile);
            trustStore.load(tsFIS, trustStorePassword.toCharArray());

            String keyStorePath = System.getProperty("javax.net.ssl.keyStore");
            String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType");
            String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");

            keyStore = KeyStore.getInstance(keyStoreType);
            File keyStoreFile = new File(keyStorePath);
            ksFIS = new FileInputStream(keyStoreFile);
            keyStore.load(ksFIS, keyStorePassword.toCharArray());

            TrustManagerFactory trustFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustFactory.init(trustStore);
            TrustManager[] tm = trustFactory.getTrustManagers();
            params.setTrustManagers(tm);

            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyFactory.init(keyStore, keyStorePassword.toCharArray());
            KeyManager[] km = keyFactory.getKeyManagers();
            params.setKeyManagers(km);

            conduit.setTlsClientParameters(params);
        } catch (KeyStoreException e) {
            handleKeyStoreException(e);
        } catch (NoSuchAlgorithmException e) {
            handleKeyStoreException(e);
        } catch (CertificateException e) {
            handleKeyStoreException(e);
        } catch (FileNotFoundException e) {
            handleKeyStoreException(e);
        } catch (IOException e) {
            handleKeyStoreException(e);
        } catch (UnrecoverableKeyException e) {
            handleKeyStoreException(e);
        } finally {
            if (null != tsFIS) {
                IOUtils.closeQuietly(tsFIS);
            }
            if (null != ksFIS) {
                IOUtils.closeQuietly(ksFIS);
            }
        }
    } else {
        LOGGER.warn("HTTP Conduit returned by the web client was NULL.");
    }
}

From source file:com.vmware.photon.controller.core.Main.java

private static PhotonControllerXenonHost startXenonHost(PhotonControllerConfig photonControllerConfig,
        ThriftModule thriftModule, DeployerConfig deployerConfig, SSLContext sslContext) throws Throwable {
    // Values for CloudStore
    final HostClientFactory hostClientFactory = thriftModule.getHostClientFactory();
    final AgentControlClientFactory agentControlClientFactory = thriftModule.getAgentControlClientFactory();
    final NsxClientFactory nsxClientFactory = new NsxClientFactory();

    // Values for Scheduler
    final ServerSet cloudStoreServerSet = new StaticServerSet(
            new InetSocketAddress(photonControllerConfig.getXenonConfig().getRegistrationAddress(),
                    Constants.PHOTON_CONTROLLER_PORT));
    final CloudStoreHelper cloudStoreHelper = new CloudStoreHelper(cloudStoreServerSet);

    final CloseableHttpAsyncClient httpClient;
    try {/* w w w  .  j  av a2s  .  co m*/
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial((chain, authtype) -> true).build();
        httpClient = HttpAsyncClientBuilder.create()
                .setHostnameVerifier(SSLIOSessionStrategy.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLContext(sslcontext)
                .build();
        httpClient.start();
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

    ServerSet apiFeServerSet = new StaticServerSet(new InetSocketAddress(
            photonControllerConfig.getXenonConfig().getRegistrationAddress(), Constants.MANAGEMENT_API_PORT));

    logger.info("Creating PhotonController Xenon Host");
    final PhotonControllerXenonHost photonControllerXenonHost = new PhotonControllerXenonHost(
            photonControllerConfig.getXenonConfig(), hostClientFactory, agentControlClientFactory,
            nsxClientFactory, cloudStoreHelper, sslContext);
    logger.info("Created PhotonController Xenon Host");

    // Set referer Uri from the xenon host, because we do not want to rely on
    // CloudStoreHelper's default mechanise to create referer based on local address,
    // because CloudStoreHelper uses InetAddress.getLocalHost() which depends on
    // /etc/hosts having a hostname entry, which is not always available.
    // This change will allow people to run this service without need to
    // update their /etc/hosts file.
    cloudStoreHelper.setRefererUri(photonControllerXenonHost.getUri());

    final ConstraintChecker checker = new CloudStoreConstraintChecker(cloudStoreHelper,
            photonControllerXenonHost);

    logger.info("Creating Cloud Store Xenon Service Group");
    CloudStoreServiceGroup cloudStoreServiceGroup = createCloudStoreServiceGroup(deployerConfig.isInstaller());
    logger.info("Created Cloud Store Xenon Service Group");

    logger.info("Registering Cloud Store Xenon Service Group");
    photonControllerXenonHost.registerCloudStore(cloudStoreServiceGroup);
    logger.info("Registered Cloud Store Xenon Service Group");

    logger.info("Creating Scheduler Xenon Service Group");
    SchedulerServiceGroup schedulerServiceGroup = createSchedulerServiceGroup(photonControllerConfig.getRoot(),
            checker);
    logger.info("Created Scheduler Xenon Service Group");

    logger.info("Registering Scheduler Xenon Service Group");
    photonControllerXenonHost.registerScheduler(schedulerServiceGroup);
    logger.info("Registered Scheduler Xenon Service Group");

    logger.info("Creating Housekeeper Xenon Service Group");
    HousekeeperServiceGroup housekeeperServiceGroup = createHousekeeperServiceGroup();
    logger.info("Created Housekeeper Xenon Service Group");

    logger.info("Registering Housekeeper Xenon Service Group");
    photonControllerXenonHost.registerHousekeeper(housekeeperServiceGroup);
    logger.info("Registered Housekeeper Xenon Service Group");

    logger.info("Creating Deployer Xenon Service Group");
    DeployerServiceGroup deployerServiceGroup = createDeployerServiceGroup(photonControllerConfig,
            deployerConfig, apiFeServerSet, cloudStoreServerSet, httpClient);
    logger.info("Created Deployer Xenon Service Group");

    logger.info("Registering Deployer Xenon Service Group");
    photonControllerXenonHost.registerDeployer(deployerServiceGroup);
    logger.info("Registered Deployer Xenon Service Group");

    DeployerContext deployerContext = deployerConfig.getDeployerContext();
    if (deployerContext.isAuthEnabled()) {
        ServiceClient serviceClient = NettyHttpServiceClient.create(Main.class.getSimpleName(),
                Executors.newFixedThreadPool(Utils.DEFAULT_THREAD_COUNT),
                Executors.newScheduledThreadPool(Utils.DEFAULT_IO_THREAD_COUNT), photonControllerXenonHost);

        /*
        To make sure that Xenon uses only TLSv1.2 and disallows SSLv3, TLSv1,
        TLSv1.1 the Docker file for the photon-controller-core container is edited.
        The java.security file located inside the container at the location
        /var/opt/OpenJDK-* /jre/lib/security has the information under the
        jdk.tls.disabledAlgorithms
        */

        SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance("JKS");
        try (FileInputStream fis = new FileInputStream(deployerContext.getKeyStorePath())) {
            keyStore.load(fis, deployerContext.getKeyStorePassword().toCharArray());
        }
        keyManagerFactory.init(keyStore, deployerContext.getKeyStorePassword().toCharArray());
        clientContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        serviceClient.setSSLContext(clientContext);
        photonControllerXenonHost.setClient(serviceClient);
    }

    logger.info("Starting PhotonController Xenon Host");
    photonControllerXenonHost.start();
    logger.info("Started PhotonController Xenon Host");

    logger.info("Creating SystemConfig instance");
    SystemConfig.createInstance(photonControllerXenonHost);
    logger.info("Created SystemConfig instance");
    return photonControllerXenonHost;
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Setup trust store for SSL client./*  w w w.  j  av  a2  s. c om*/
 */
private void setupTrustStore(TLSClientParameters tlsParams, String trustStorePath, String trustStorePassword) {
    File trustStoreFile = new File(trustStorePath);
    if (trustStoreFile.exists() && trustStorePassword != null) {
        KeyStore trustStore = null;
        FileInputStream fis = null;

        try {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            fis = new FileInputStream(trustStoreFile);
            LOGGER.debug("Loading trustStore");
            trustStore.load(fis, trustStorePassword.toCharArray());
            TrustManagerFactory trustFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustFactory.init(trustStore);
            LOGGER.debug("trust manager factory initialized");
            TrustManager[] tm = trustFactory.getTrustManagers();
            tlsParams.setTrustManagers(tm);

        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to find SSL store: " + trustStorePath, e);
        } catch (IOException e) {
            LOGGER.error("Unable to load trust store. " + trustStore, e);
        } catch (CertificateException e) {
            LOGGER.error("Unable to load certificates from trust store. " + trustStore, e);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read trust store: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }
}