Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

In this page you can find the example usage for java.security KeyStore getCertificate.

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

@TestOrderAnnotation(order = 14)
@Test/*from  w ww .ja  v a  2s  .c  o m*/
public void testSetTenantTrustedCertChain() throws Exception, IDMException {
    CasIdmClient idmClient = getIdmClient();

    Properties props = getTestProperties();

    // Set trustedCertChain for non-system tenant
    String tenantName = props.getProperty(CFG_KEY_IDM_TENANT_1_NAME);

    Assert.assertNotNull(tenantName);

    Tenant tenant = IdmClientTestUtil.ensureTenantExists(idmClient, tenantName);

    Assert.assertNotNull(tenant);

    List<Certificate> certList = new ArrayList<Certificate>();

    KeyStore ks = loadKeyStore(CFG_KEY_TRUSTED_STS_KEYSTORE, CFG_KEY_TRUSTED_STS_KEYSTORE_PASSWORD);

    String alias = props.getProperty(CFG_KEY_TRUSTED_STS_KEY_ALIAS);
    Assert.assertNotNull(alias);
    certList.add(ks.getCertificate(alias));

    String alias1 = props.getProperty(CFG_KEY_TRUSTED_STS_KEY_ALIAS1);
    Assert.assertNotNull(alias1);
    certList.add(ks.getCertificate(alias1));

    Collection<List<Certificate>> certList_prev = idmClient.getTenantCertificates(tenantName);
    idmClient.setTenantTrustedCertificateChain(tenantName, certList);
    Collection<List<Certificate>> certList_after = idmClient.getTenantCertificates(tenantName);

    Assert.assertTrue(certList_after.contains(certList));
    Assert.assertTrue(certList_prev.size() + 1 == certList_after.size());

    // Set trustedCertChain for system tenant
    List<Certificate> certList1 = new ArrayList<Certificate>();

    ks = loadKeyStore(CFG_KEY_STS_KEYSTORE, CFG_KEY_STS_KEYSTORE_PASSWORD);

    alias = props.getProperty(CFG_KEY_STS_KEY_ALIAS);
    Assert.assertNotNull(alias);
    Certificate trusted_leaf_cert = ks.getCertificate(alias);
    certList1.add(trusted_leaf_cert);

    alias1 = props.getProperty(CFG_KEY_STS_KEY_ALIAS1);
    Assert.assertNotNull(alias1);
    Certificate trusted_root_cert = ks.getCertificate(alias1);
    certList1.add(trusted_root_cert);

    String system_tenantName = props.getProperty(CFG_KEY_IDM_SYSTEM_TENANT_NAME);
    Assert.assertNotNull(system_tenantName);
    String obtainedSysTenant = idmClient.getSystemTenant();
    Assert.assertTrue(system_tenantName.equalsIgnoreCase(obtainedSysTenant));

    Collection<List<Certificate>> certList_prev_sp = idmClient.getTenantCertificates(system_tenantName);
    idmClient.setTenantTrustedCertificateChain(system_tenantName, certList1);
    Collection<List<Certificate>> certList_after_sp = idmClient.getTenantCertificates(system_tenantName);

    Assert.assertTrue(certList_after_sp.contains(certList1));
    Assert.assertTrue(certList_prev_sp.size() + 1 == certList_after_sp.size());

    Collection<Certificate> allLdapCerts = idmClient.getAllCertificates(system_tenantName,
            CertificateType.LDAP_TRUSTED_CERT);
    Assert.assertTrue(allLdapCerts == null || allLdapCerts.size() == 0);
    Collection<Certificate> allStsCerts = idmClient.getAllCertificates(system_tenantName,
            CertificateType.STS_TRUST_CERT);

    Collection<Certificate> rootCerts = idmClient.getTrustedCertificates(system_tenantName);
    Assert.assertTrue(rootCerts.contains(trusted_root_cert));

    Collection<Certificate> leafCerts = idmClient.getStsIssuersCertificates(system_tenantName);
    Assert.assertTrue(leafCerts.contains(trusted_leaf_cert));

    // clean up added TrustedCertificateChain
    idmClient.deleteCertificate(system_tenantName,
            CertificateUtil.generateFingerprint((X509Certificate) trusted_root_cert),
            CertificateType.STS_TRUST_CERT);

    // Make sure 'trusted_root_cert' is removed successfully
    allStsCerts = idmClient.getAllCertificates(system_tenantName, CertificateType.STS_TRUST_CERT);
    Assert.assertFalse(allStsCerts.contains(trusted_root_cert));

    rootCerts = idmClient.getTrustedCertificates(system_tenantName);
    Assert.assertTrue(rootCerts.size() == 1);

    leafCerts = idmClient.getStsIssuersCertificates(system_tenantName);
    Assert.assertTrue(leafCerts.size() == 1);

    // Make sure 'trustedCertChain is removed (triggered by trustedRoot Cert removal)
    Collection<List<Certificate>> certChains = idmClient.getTenantCertificates(system_tenantName);
    // certChain used in 'TenantTest' has two elements (sorted by leaf followed by root)
    for (List<Certificate> certChain : certChains) {
        boolean bcertChainExist = certChain.get(0).equals(trusted_leaf_cert)
                && certChain.get(1).equals(trusted_root_cert);
        Assert.assertFalse(bcertChainExist);
    }

    return;
}

From source file:com.vmware.identity.idm.client.TenantManagementTest.java

@TestOrderAnnotation(order = 49)
@Test//from   w ww  .ja va 2s.co  m
public void testSetGetTenantProperties() throws Exception, IDMException {
    CasIdmClient idmClient = getIdmClient();

    Properties props = getTestProperties();

    String testTenantName = props.getProperty(CFG_KEY_IDM_TENANT_2_NAME);
    Assert.assertNotNull(testTenantName);

    IdmClientTestUtil.ensureTenantDoesNotExist(idmClient, testTenantName);

    Tenant tenant = IdmClientTestUtil.ensureTenantExists(idmClient, testTenantName);
    Assert.assertNotNull(tenant);

    final long clockTolerance = 20000;
    idmClient.setClockTolerance(testTenantName, clockTolerance);
    Assert.assertEquals(clockTolerance, idmClient.getClockTolerance(testTenantName));

    final int delegationCount = 5;
    idmClient.setDelegationCount(testTenantName, delegationCount);
    Assert.assertEquals(delegationCount, idmClient.getDelegationCount(testTenantName));

    final int renewCount = 10;
    idmClient.setRenewCount(testTenantName, renewCount);
    Assert.assertEquals(renewCount, idmClient.getRenewCount(testTenantName));

    final long maxhoktoken = 30000;
    idmClient.setMaximumHoKTokenLifetime(testTenantName, maxhoktoken);
    Assert.assertEquals(maxhoktoken, idmClient.getMaximumHoKTokenLifetime(testTenantName));

    final long maxbeartoken = 40000;
    idmClient.setMaximumBearerTokenLifetime(testTenantName, maxbeartoken);
    Assert.assertEquals(maxbeartoken, idmClient.getMaximumBearerTokenLifetime(testTenantName));

    final long maxBearerRefreshTokenLifeTime = 40000;
    idmClient.setMaximumBearerRefreshTokenLifetime(testTenantName, maxBearerRefreshTokenLifeTime);
    Assert.assertEquals(maxbeartoken, idmClient.getMaximumBearerRefreshTokenLifetime(testTenantName));

    final long maxHoKRefreshTokenLifeTime = 30000;
    idmClient.setMaximumHoKRefreshTokenLifetime(testTenantName, maxHoKRefreshTokenLifeTime);
    Assert.assertEquals(maxhoktoken, idmClient.getMaximumHoKRefreshTokenLifetime(testTenantName));

    final String signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
    idmClient.setTenantSignatureAlgorithm(testTenantName, signatureAlgorithm);
    Assert.assertEquals(signatureAlgorithm, idmClient.getTenantSignatureAlgorithm(testTenantName));

    final String brandName = "Acme single sign-on";
    idmClient.setBrandName(testTenantName, brandName);
    String retrievedBrand = idmClient.getBrandName(testTenantName);
    Assert.assertEquals(brandName, retrievedBrand);

    String testLogonBannerTitle = "Acme logon banner";
    String testLogonBannerContent = "This is a disclaimer.";
    idmClient.setLogonBannerTitle(testTenantName, testLogonBannerTitle);
    idmClient.setLogonBannerContent(testTenantName, testLogonBannerContent);
    idmClient.setLogonBannerCheckboxFlag(testTenantName, true);
    String retrievedLogonBannerContent = idmClient.getLogonBannerContent(testTenantName);
    String retrievedLogonBannerTitle = idmClient.getLogonBannerTitle(testTenantName);
    Assert.assertEquals(retrievedLogonBannerTitle, testLogonBannerTitle);
    Assert.assertEquals(retrievedLogonBannerContent, testLogonBannerContent);
    Assert.assertTrue(idmClient.getLogonBannerCheckboxFlag(testTenantName));

    final String entityId = "EntityId";
    idmClient.setEntityID(testTenantName, entityId);
    Assert.assertEquals(entityId, idmClient.getEntityID(testTenantName));

    final String alias = "vsphere.local";
    idmClient.setLocalIDPAlias(testTenantName, alias);
    Assert.assertEquals(alias, idmClient.getLocalIDPAlias(testTenantName));
    idmClient.setLocalIDPAlias(testTenantName, null);
    Assert.assertNull(idmClient.getLocalIDPAlias(testTenantName));

    Assert.assertTrue(idmClient.isTenantIDPSelectionEnabled(testTenantName));
    boolean enableIdpSelection = false;
    idmClient.setTenantIDPSelectionEnabled(testTenantName, enableIdpSelection);
    Assert.assertFalse(idmClient.isTenantIDPSelectionEnabled(testTenantName));

    PasswordExpiration expiration = new PasswordExpiration(true, "a@abc.com", "Password Expired",
            new int[] { 1, 3, 5 });

    idmClient.updatePasswordExpirationConfiguration(testTenantName, expiration);
    PasswordExpiration expiration1 = idmClient.getPasswordExpirationConfiguration(testTenantName);

    Assert.assertNotNull(expiration1);
    Assert.assertEquals(expiration.isEmailNotificationEnabled(), expiration1.isEmailNotificationEnabled());
    Assert.assertEquals(expiration.getEmailFrom(), expiration1.getEmailFrom());
    Assert.assertEquals(expiration.getEmailSubject(), expiration1.getEmailSubject());

    int[] days = expiration1.getNotificationDays();
    Assert.assertNotNull(days);
    Assert.assertEquals(expiration.getNotificationDays().length, days.length);
    int i = 0;
    for (int day : expiration.getNotificationDays()) {
        Assert.assertEquals(day, days[i]);
        i++;
    }

    // idm cert
    KeyStore ks = loadKeyStore(CFG_KEY_STS_KEYSTORE, CFG_KEY_STS_KEYSTORE_PASSWORD);
    X509Certificate cert = (X509Certificate) ks.getCertificate(props.getProperty(CFG_KEY_STS_KEY_ALIAS));

    // add cert of type 'LDAP_TRUSTED_CERT'
    idmClient.addCertificate(testTenantName, cert, CertificateType.LDAP_TRUSTED_CERT);

    Collection<Certificate> idmCertificates = idmClient.getAllCertificates(testTenantName,
            CertificateType.LDAP_TRUSTED_CERT);
    Assert.assertNotNull(idmCertificates);
    Assert.assertEquals(1, idmCertificates.size());

    X509Certificate cert1 = (X509Certificate) ks.getCertificate(props.getProperty(CFG_KEY_STS_KEY_ALIAS1));

    // add cert of type 'STS_TRUSTED_CERT'
    idmClient.addCertificate(testTenantName, cert1, CertificateType.STS_TRUST_CERT);

    idmCertificates = idmClient.getAllCertificates(testTenantName, CertificateType.STS_TRUST_CERT);
    Assert.assertNotNull(idmCertificates);
    Assert.assertEquals(1, idmCertificates.size());

    // delete cert of type 'LDAP_TRUSTED_CERT'
    idmClient.deleteCertificate(testTenantName, CertificateUtil.generateFingerprint(cert),
            CertificateType.LDAP_TRUSTED_CERT);
    idmCertificates = idmClient.getAllCertificates(testTenantName, CertificateType.LDAP_TRUSTED_CERT);
    Assert.assertEquals(true, ((idmCertificates == null) || (idmCertificates.size() == 0)));

    // should still have 'sts' trust cert
    idmCertificates = idmClient.getAllCertificates(testTenantName, CertificateType.STS_TRUST_CERT);
    Assert.assertNotNull(idmCertificates);
    Assert.assertEquals(1, idmCertificates.size());

    // delete cert of type 'STS_TRUSTED_CERT'
    idmClient.deleteCertificate(testTenantName, CertificateUtil.generateFingerprint(cert1),
            CertificateType.STS_TRUST_CERT);
    idmCertificates = idmClient.getAllCertificates(testTenantName, CertificateType.STS_TRUST_CERT);
    Assert.assertEquals(true, ((idmCertificates == null) || (idmCertificates.size() == 0)));

    // default provider
    final String adProviderName = props.getProperty(CFG_KEY_IDM_TENANT_1_AD_PROVIDER_DOMAIN_NAME);
    Assert.assertNotNull(adProviderName);

    final String adProviderAlias = props.getProperty(CFG_KEY_IDM_TENANT_1_AD_PROVIDER_ALIAS);
    Assert.assertNotNull(adProviderAlias);

    IdentityStoreData adStore = IdmClientTestUtil.prepareADIdentityStore(idmClient, true);
    IIdentityStoreData store = idmClient.getProvider(testTenantName, adProviderName);

    // check before create
    if (store == null) {
        idmClient.addProvider(testTenantName, adStore);
    }

    // set using providerName
    idmClient.setDefaultProviders(testTenantName, Arrays.asList(new String[] { adProviderName }));

    Collection<String> providers = idmClient.getDefaultProviders(testTenantName);
    Assert.assertNotNull(providers);
    Assert.assertEquals(1, providers.size());
    Assert.assertEquals(adProviderName, providers.iterator().next());

    idmClient.deleteProvider(testTenantName, adProviderName);
    providers = idmClient.getDefaultProviders(testTenantName);
    Assert.assertTrue(((providers == null) || (providers.size() == 0)));

    store = idmClient.getProvider(testTenantName, adProviderName);

    // check before create
    if (store == null) {
        idmClient.addProvider(testTenantName, adStore);
    }

    // set using provider Alias Name
    idmClient.setDefaultProviders(testTenantName, Arrays.asList(new String[] { adProviderAlias }));
    providers = idmClient.getDefaultProviders(testTenantName);
    Assert.assertNotNull(providers);
    Assert.assertEquals(1, providers.size());
    Assert.assertEquals(adProviderAlias, providers.iterator().next());

    idmClient.setDefaultProviders(testTenantName, null);
    providers = idmClient.getDefaultProviders(testTenantName);
    Assert.assertTrue(((providers == null) || (providers.size() == 0)));

    idmClient.deleteProvider(testTenantName, adProviderAlias);
    providers = idmClient.getDefaultProviders(testTenantName);
    Assert.assertTrue(((providers == null) || (providers.size() == 0)));

    // default tenant
    String defaultTenant = idmClient.getDefaultTenant();

    idmClient.setDefaultTenant(testTenantName);
    Assert.assertEquals(testTenantName, idmClient.getDefaultTenant());

    idmClient.deleteTenant(testTenantName);
    String defTenant = idmClient.getDefaultTenant();
    Assert.assertTrue((defTenant == null) || (defTenant.isEmpty()));

    if ((defaultTenant != testTenantName) && (defaultTenant != null) && (defaultTenant.isEmpty() == false)) {
        idmClient.setDefaultTenant(defaultTenant);
        Assert.assertEquals(defaultTenant, idmClient.getDefaultTenant());
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Load Taverna's Truststore from a file on a disk. If the Truststore does
 * not already exist, a new empty one will be created and contents of Java's
 * truststore located in <JAVA_HOME>/lib/security/cacerts will be copied
 * over to the Truststore./*  w  ww  .  j a v  a  2s .c  o m*/
 */
private void loadTruststore() throws CMException {
    if (truststore != null)
        return;
    try {
        /*
         * Try to create Taverna's Truststore as Bouncy Castle UBER-type
         * keystore.
         */
        truststore = KeyStore.getInstance("UBER", "BC");
    } catch (Exception ex) {
        /*
         * The requested keystore type is not available from security
         * providers.
         */
        throw new CMException("Failed to instantiate Taverna's Truststore", ex);
    }

    if (truststoreFile.exists()) {
        /*
         * If the Truststore file already exists, open it and load the
         * Truststore
         */
        try (FileInputStream fis = new FileInputStream(truststoreFile)) {
            // Load the Truststore from the file
            truststore.load(fis, masterPassword.toCharArray());
        } catch (Exception ex) {
            /* Clear out things that are useless/hindering now */
            truststore = null;
            masterPassword = null;
            String exMessage = "Failed to load Taverna's Truststore from " + truststoreFile.getAbsolutePath()
                    + ". Possible reason: incorrect password or corrupted file.";
            logger.error(exMessage, ex);
            throw new CMException(exMessage, ex);
        }
        deleteRevokedCertificates();
    } else {
        /*
         * Otherwise create a new empty Truststore and load it with certs
         * from Java's truststore.
         */
        File javaTruststoreFile = new File(System.getProperty("java.home"), "lib/security/cacerts");
        KeyStore javaTruststore = null;

        // Java's truststore is of type "JKS" - try to load it
        try {
            javaTruststore = KeyStore.getInstance("JKS");
        } catch (Exception ex) {
            // The requested keystore type is not available from the
            // provider
            throw new CMException(
                    "Failed to instantiate a 'JKS'-type keystore " + "for reading Java's truststore.", ex);
        }

        boolean loadedJavaTruststore = false;
        /*
         * Load Java's truststore from the file - try with the default Java
         * truststore passwords.
         */
        for (String password : defaultTrustStorePasswords) {
            logger.info("Trying to load Java truststore using password: " + password);
            try (FileInputStream fis = new FileInputStream(javaTruststoreFile)) {
                javaTruststore.load(fis, password.toCharArray());
                loadedJavaTruststore = true;
                break;
            } catch (IOException ioex) {
                /*
                 * If there is an I/O or format problem with the keystore
                 * data, or if the given password was incorrect. (Thank you
                 * Sun, now I can't know if it is the file or the
                 * password..)
                 */
                logger.info(String.format(
                        "Failed to load the Java truststore to copy "
                                + "over certificates using default password: " + "%s from %s",
                        password, javaTruststoreFile));
            } catch (NoSuchAlgorithmException e) {
                logger.error("Unknown encryption algorithm " + "while loading Java truststore from "
                        + javaTruststoreFile, e);
                break;
            } catch (CertificateException e) {
                logger.error("Certificate error while " + "loading Java truststore from " + javaTruststoreFile,
                        e);
                break;
            }
        }

        /*
         * Default Java truststore passwords failed - possibly the user has
         * changed it. Ask the Java truststore password providers if they
         * can help - this will typically pop up a dialog to ask the user if
         * we are in a graphical environment. If not, we will simply not
         * copy the default truststore certificates into Credential
         * Manager's Truststore.
         */
        if (!loadedJavaTruststore
                && !loadJavaTruststoreUsingPasswordProviders(javaTruststore, javaTruststoreFile)) {
            String error = "Credential manager failed to load" + " certificates from Java's truststore.";
            String help = "Try using the system property -D" + PROPERTY_TRUSTSTORE_PASSWORD
                    + "=TheTrustStorePassword";
            logger.error(error + " " + help);
            // FIXME Writes to standard error!
            System.err.println(error);
            System.err.println(help);
        }

        // Create a new empty Truststore for Taverna
        try (FileOutputStream fos = new FileOutputStream(truststoreFile)) {
            truststore.load(null, null);
            if (loadedJavaTruststore) {
                // Copy certificates into Taverna's Truststore from
                // Java's truststore.
                Enumeration<String> aliases = javaTruststore.aliases();
                while (aliases.hasMoreElements()) {
                    Certificate certificate = javaTruststore.getCertificate(aliases.nextElement());
                    if (certificate instanceof X509Certificate)
                        truststore.setCertificateEntry(
                                createTrustedCertificateAlias((X509Certificate) certificate), certificate);
                }
            }

            // Insert special trusted CA certificates
            logger.info(
                    "Loading certificates of trusted CAs so as to establish trust into our services such as BioCatalogue, BiodiversityCatalogue, heater, etc.");
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            for (URL trustedCertURL : getSpecialTrustedCertificates())
                // Load the certificate (possibly a chain) from the
                // stream
                try (InputStream stream = trustedCertURL.openStream()) {
                    for (Certificate c : cf.generateCertificates(stream))
                        truststore.setCertificateEntry(createTrustedCertificateAlias((X509Certificate) c), c);
                } catch (Exception cex) {
                    logger.error("Failed to insert trusted certificate entry in the Truststore", cex);
                }

            // Immediately save the new Truststore to the file
            truststore.store(fos, masterPassword.toCharArray());
        } catch (Exception ex) {
            /*
             * make truststore null as it was just created but failed to
             * save so we should retry next time
             */
            truststore = null;
            throw new CMException("Failed to generate new empty Taverna's Truststore", ex);
        }
    }

    /*
     * Taverna distro for MAC contains info.plist file with some Java system
     * properties set to use the Keychain which clashes with what we are
     * setting here so we need to clear them.
     */
    System.clearProperty(PROPERTY_TRUSTSTORE_TYPE);
    System.clearProperty(PROPERTY_TRUSTSTORE_PROVIDER);

    /*
     * Not quite sure why we still need to set these two properties since we
     * are creating our own SSLSocketFactory with our own TrustManager that
     * uses Taverna's Truststore, but seem like after Taverna starts up and
     * the first time it needs SSLSocketFactory for HTTPS connection it is
     * still using the default Java's truststore unless these properties are
     * set. Set the system property "javax.net.ssl.Truststore" to use
     * Taverna's truststore.
     */

    /*
     * Axis 1 likes reading from these properties but seems to work as well
     * with Taverna's SSLSocetFactory as well. We do not want to expose
     * these as they can be read from Beanshells.
     */
    // System.setProperty(PROPERTY_TRUSTSTORE, truststoreFile.getAbsolutePath());
    // System.setProperty(PROPERTY_TRUSTSTORE_PASSWORD, masterPassword);
    System.clearProperty(PROPERTY_TRUSTSTORE);
    System.clearProperty(PROPERTY_TRUSTSTORE_PASSWORD);
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Load Taverna's Truststore from a file on a disk. If the Truststore does
 * not already exist, a new empty one will be created and contents of Java's
 * truststore located in <JAVA_HOME>/lib/security/cacerts will be copied
 * over to the Truststore./*from  w  w  w .  j a  v a 2s.  co  m*/
 */
private void loadTruststore() throws CMException {
    if (truststore == null) {
        try {
            // Try to create Taverna's Truststore as Bouncy Castle UBER-type
            // keystore.
            truststore = KeyStore.getInstance("UBER", "BC");
        } catch (Exception ex) {
            // The requested keystore type is not available from security
            // providers.
            throw new CMException("Failed to instantiate Taverna's Truststore", ex);
        }

        if (truststoreFile.exists()) {
            // If the Truststore file already exists, open it and load the
            // Truststore
            try (FileInputStream fis = new FileInputStream(truststoreFile)) {
                // Load the Truststore from the file
                truststore.load(fis, masterPassword.toCharArray());

                // Delete the old revoked or unnecessary BioCatalogue,
                // BiodiversityCatalogue and heater's certificates, if present
                deleteRevokedCertificates();

            } catch (Exception ex) {
                /* Clear out things that are useless/hindering now */
                truststore = null;
                masterPassword = null;
                String exMessage = "Failed to load Taverna's Truststore from "
                        + truststoreFile.getAbsolutePath()
                        + ". Possible reason: incorrect password or corrupted file.";
                logger.error(exMessage, ex);
                throw new CMException(exMessage, ex);
            }
        } else {
            /*
             * Otherwise create a new empty Truststore and load it with
             * certs from Java's truststore.
             */
            File javaTruststoreFile = new File(System.getProperty("java.home"), "lib/security/cacerts");
            KeyStore javaTruststore = null;

            // Java's truststore is of type "JKS" - try to load it
            try {
                javaTruststore = KeyStore.getInstance("JKS");
            } catch (Exception ex) {
                // The requested keystore type is not available from the
                // provider
                throw new CMException(
                        "Failed to instantiate a 'JKS'-type keystore " + "for reading Java's truststore.", ex);
            }

            boolean loadedJavaTruststore = false;
            /*
             * Load Java's truststore from the file - try with the default
             * Java truststore passwords.
             */
            for (String password : defaultTrustStorePasswords) {
                logger.info("Trying to load Java truststore using password: " + password);
                try (FileInputStream fis = new FileInputStream(javaTruststoreFile)) {
                    javaTruststore.load(fis, password.toCharArray());
                    loadedJavaTruststore = true;
                    break;
                } catch (IOException ioex) {
                    /*
                     * If there is an I/O or format problem with the
                     * keystore data, or if the given password was incorrect
                     * (Thank you Sun, now I can't know if it is the file or
                     * the password..)
                     */
                    logger.info(String.format(
                            "Failed to load the Java truststore to copy "
                                    + "over certificates using default password: " + "%s from %s",
                            password, javaTruststoreFile));
                } catch (NoSuchAlgorithmException e) {
                    logger.error("Unknown encryption algorithm " + "while loading Java truststore from "
                            + javaTruststoreFile, e);
                    break;
                } catch (CertificateException e) {
                    logger.error(
                            "Certificate error while " + "loading Java truststore from " + javaTruststoreFile,
                            e);
                    break;
                }
            }

            /*
             * Default Java truststore passwords failed - possibly the user
             * has changed it. Ask the Java truststore password providers if
             * they can help - this will typically pop up a dialog to ask
             * the user if we are in a graphical environment. If not, we
             * will simply not copy the default truststore certificates into
             * Credential Manager's Truststore.
             */
            if (!loadedJavaTruststore)
                if (!(loadJavaTruststoreUsingPasswordProviders(javaTruststore, javaTruststoreFile))) {
                    String error = "Credential manager failed to load"
                            + " certificates from Java's truststore.";
                    String help = "Try using the system property -D" + PROPERTY_TRUSTSTORE_PASSWORD
                            + "=TheTrustStorePassword";
                    logger.error(error + " " + help);
                    // FIXME Writes to standard error!
                    System.err.println(error);
                    System.err.println(help);
                }

            // Create a new empty Truststore for Taverna
            try (FileOutputStream fos = new FileOutputStream(truststoreFile)) {
                truststore.load(null, null);
                if (loadedJavaTruststore) {
                    // Copy certificates into Taverna's Truststore from
                    // Java's truststore.
                    Enumeration<String> aliases = javaTruststore.aliases();
                    while (aliases.hasMoreElements()) {
                        Certificate certificate = javaTruststore.getCertificate(aliases.nextElement());
                        if (certificate instanceof X509Certificate)
                            truststore.setCertificateEntry(
                                    createTrustedCertificateAlias((X509Certificate) certificate), certificate);
                    }
                }

                // Insert special trusted CA certificates
                logger.info(
                        "Loading certificates of trusted CAs so as to establish trust into our services such as BioCatalogue, BiodiversityCatalogue, heater, etc.");
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                for (URL trustedCertURL : getSpecialTrustedCertificates())
                    // Load the certificate (possibly a chain) from the
                    // stream
                    try (InputStream stream = trustedCertURL.openStream()) {
                        for (Certificate c : cf.generateCertificates(stream))
                            truststore.setCertificateEntry(createTrustedCertificateAlias((X509Certificate) c),
                                    c);
                    } catch (Exception cex) {
                        logger.error("Failed to insert trusted certificate entry in the Truststore", cex);
                    }

                // Immediately save the new Truststore to the file
                truststore.store(fos, masterPassword.toCharArray());
            } catch (Exception ex) {
                /*
                 * make truststore null as it was just created but failed to
                 * save so we should retry next time
                 */
                truststore = null;
                throw new CMException("Failed to generate new empty Taverna's Truststore", ex);
            }
        }

        /*
         * Taverna distro for MAC contains info.plist file with some Java
         * system properties set to use the Keychain which clashes with what
         * we are setting here so we need to clear them.
         */
        System.clearProperty(PROPERTY_TRUSTSTORE_TYPE);
        System.clearProperty(PROPERTY_TRUSTSTORE_PROVIDER);

        /*
         * Not quite sure why we still need to set these two properties
         * since we are creating our own SSLSocketFactory with our own
         * TrustManager that uses Taverna's Truststore, but seem like after
         * Taverna starts up and the first time it needs SSLSocketFactory
         * for HTTPS connection it is still using the default Java's
         * truststore unless these properties are set. Set the system
         * property "javax.net.ssl.Truststore" to use Taverna's truststore.
         */

        /*
         * Axis 1 likes reading from these properties but seems to work as
         * well with Taverna's SSLSocetFactory as well. We do not want to
         * expose these as they can be read from Beanshells.
         */
        // System.setProperty(PROPERTY_TRUSTSTORE, truststoreFile.getAbsolutePath());
        // System.setProperty(PROPERTY_TRUSTSTORE_PASSWORD, masterPassword);
        System.clearProperty(PROPERTY_TRUSTSTORE);
        System.clearProperty(PROPERTY_TRUSTSTORE_PASSWORD);
    }
}