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:org.apache.cassandra.hadoop.cql3.CqlConfigHelper.java

private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath,
        String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    SSLContext ctx;//from  w ww. ja  v a2  s. c om
    try (FileInputStream tsf = new FileInputStream(truststorePath);
            FileInputStream ksf = new FileInputStream(keystorePath)) {
        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:com.liferay.sync.engine.lan.session.LanSession.java

private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception {

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

    keyStore.load(null, null);/*from  w w  w  .j  a  v a 2 s.  c  om*/

    for (SyncAccount syncAccount : SyncAccountService.findAll()) {
        if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) {
            continue;
        }

        try {
            PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey());

            if (privateKey == null) {
                _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId());

                continue;
            }

            X509Certificate x509Certificate = LanPEMParserUtil
                    .parseX509Certificate(syncAccount.getLanCertificate());

            if (x509Certificate == null) {
                _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId());

                continue;
            }

            keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate);

            keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(),
                    new Certificate[] { x509Certificate });
        } catch (Exception e) {
            _logger.error(e.getMessage(), e);
        }
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());

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

    trustManagerFactory.init(keyStore);

    SSLContext sslContext = SSLContext.getInstance("TLS");

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

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 {//from  w  ww  .j  a va 2 s . c  o  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:com.micromux.cassandra.jdbc.CassandraConnection.java

private static SSLContext getSSLContext(String trustPath, String trustPass)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException {

    FileInputStream tsf = null;//from   www.ja v  a 2  s  .c  o  m
    SSLContext ctx = null;

    try {

        tsf = new FileInputStream(trustPath);
        ctx = SSLContext.getInstance("SSL");

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

        ctx.init(null, tmf.getTrustManagers(), new SecureRandom());

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (tsf != null) {
            try {
                tsf.close();
            } catch (IOException ix) {
                logger.warn("Error Closing Trust Store: " + trustPath, ix);
            }
        }

    }

    return ctx;

}

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/*  w  w w.ja  v 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.hadoop.hdfsproxy.ProxyUtil.java

private static void setupSslProps(Configuration conf) throws IOException {
    FileInputStream fis = null;/*  ww w .  ja  va  2  s  . com*/
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        KeyManager[] kms = null;
        TrustManager[] tms = null;
        if (conf.get("ssl.client.keystore.location") != null) {
            // initialize default key manager with keystore file and pass
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            KeyStore ks = KeyStore.getInstance(conf.get("ssl.client.keystore.type", "JKS"));
            char[] ksPass = conf.get("ssl.client.keystore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.keystore.location", "keystore.jks"));
            ks.load(fis, ksPass);
            kmf.init(ks, conf.get("ssl.client.keystore.keypassword", "changeit").toCharArray());
            kms = kmf.getKeyManagers();
            fis.close();
            fis = null;
        }
        // initialize default trust manager with keystore file and pass
        if (conf.getBoolean("ssl.client.do.not.authenticate.server", false)) {
            // by pass trustmanager validation
            tms = new DummyTrustManager[] { new DummyTrustManager() };
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
            KeyStore ts = KeyStore.getInstance(conf.get("ssl.client.truststore.type", "JKS"));
            char[] tsPass = conf.get("ssl.client.truststore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.truststore.location", "truststore.jks"));
            ts.load(fis, tsPass);
            tmf.init(ts);
            tms = tmf.getTrustManagers();
        }
        sc.init(kms, tms, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        throw new IOException("Could not initialize SSLContext", e);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}

From source file:net.i2p.util.I2PSSLSocketFactory.java

/**
 *  Loads certs from/*w  w  w.  j av  a 2s  .  c  o m*/
 *  the ~/.i2p/certificates/ and $I2P/certificates/ directories.
 */
private static SSLSocketFactory initSSLContext(I2PAppContext context, boolean loadSystemCerts,
        String relativeCertPath) throws GeneralSecurityException {
    Log log = context.logManager().getLog(I2PSSLSocketFactory.class);
    KeyStore ks;
    if (loadSystemCerts) {
        ks = KeyStoreUtil.loadSystemKeyStore();
        if (ks == null)
            throw new GeneralSecurityException("Key Store init error");
    } else {
        try {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, "".toCharArray());
        } catch (IOException ioe) {
            throw new GeneralSecurityException("Key Store init error", ioe);
        }
    }

    File dir = new File(context.getConfigDir(), relativeCertPath);
    int adds = KeyStoreUtil.addCerts(dir, ks);
    int totalAdds = adds;
    if (adds > 0) {
        if (log.shouldLog(Log.INFO))
            log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath());
    }

    File dir2 = new File(context.getBaseDir(), relativeCertPath);
    if (!dir.getAbsolutePath().equals(dir2.getAbsolutePath())) {
        adds = KeyStoreUtil.addCerts(dir2, ks);
        totalAdds += adds;
        if (adds > 0) {
            if (log.shouldLog(Log.INFO))
                log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath());
        }
    }
    if (totalAdds > 0 || loadSystemCerts) {
        if (log.shouldLog(Log.INFO))
            log.info("Loaded total of " + totalAdds + " new trusted certificates");
    } else {
        String msg = "No trusted certificates loaded (looked in " + dir.getAbsolutePath()
                + (dir.getAbsolutePath().equals(dir2.getAbsolutePath()) ? ""
                        : (" and " + dir2.getAbsolutePath()))
                + ", SSL connections will fail. " + "Copy the cert in " + relativeCertPath
                + " from the router to the directory.";
        // don't continue, since we didn't load the system keystore, we have nothing.
        throw new GeneralSecurityException(msg);
    }

    SSLContext sslc = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    sslc.init(null, tmf.getTrustManagers(), context.random());
    return sslc.getSocketFactory();
}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

public static TrustKeyStore loadTrustKeyStore(InputStream keyStoreStream, String keyStorePass) {
    try {/*  w  w w  . j a v a  2 s.  c o m*/
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(keyStoreStream, keyStorePass.toCharArray());
        tmf.init(ks);
        return new TrustKeyStore(tmf);
    } catch (Exception e) {
        logger.error("loadTrustCertFactory fail : " + e.getMessage(), e);
        return null;
    }
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport,
        final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keystore);
    final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0];
    final MyTrustManager tm = new MyTrustManager(dtm);
    context.init(null, new TrustManager[] { tm }, null);
    final SSLSocketFactory factory = context.getSocketFactory();
    final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport);
    socket.setSoTimeout(10000);//  w w  w  . j av a 2 s  .com
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println("Certificate for server " + sitehostname + " is already trusted");
    } catch (SSLException e) {
        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.err.println("Could not obtain server certificate chain");
            return keystore;
        }
        System.out.println("Server sent " + chain.length + " certificate(s):");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            MessageDigest.getInstance("SHA1").update(cert.getEncoded());
            MessageDigest.getInstance("MD5").update(cert.getEncoded());
            final String alias = sitehostname + "-" + (i + 1);
            keystore.setCertificateEntry(alias, cert);
            System.out.println("Added certificate to keystore using alias '" + alias + "'");
        }
    }
    return keystore;
}

From source file:org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils.java

/**
 * Initializes the SSL Context/*from  www .  j  av  a2s. com*/
 */
private static 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);
}