Example usage for java.security KeyStore aliases

List of usage examples for java.security KeyStore aliases

Introduction

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

Prototype

public final Enumeration<String> aliases() throws KeyStoreException 

Source Link

Document

Lists all the alias names of this keystore.

Usage

From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Remove all saved passwords and keys//from  w w w .j  ava  2 s.  c  o m
 */
public synchronized void removeAllSavedPasswords() {
    getPrefs().edit().clear().apply();
    if (isAvailable()) {
        try {
            KeyStore keyStore = getKeystore();
            for (String key : Collections.list(keyStore.aliases())) {
                PasswdSafeUtil.dbginfo(TAG, "removeAllSavedPasswords key: %s", key);
                keyStore.deleteEntry(key);
            }
        } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.wso2.carbon.security.ui.client.KeyStoreAdminClient.java

public boolean isPrivateKeyStore(byte[] content, String password, String type) throws java.lang.Exception {
    try {/*from ww w.  j  av  a  2 s  .c  o  m*/
        boolean isPrivateStore = false;
        ByteArrayInputStream stream = new ByteArrayInputStream(content);
        KeyStore store = KeyStore.getInstance(type);
        store.load(stream, password.toCharArray());
        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String value = aliases.nextElement();
            if (store.isKeyEntry(value)) {
                isPrivateStore = true;
                break;
            }
        }
        return isPrivateStore;
    } catch (java.lang.Exception e) {
        log.error("Error in checking private key store.", e);
        throw e;
    }
}

From source file:nl.b3p.viewer.admin.stripes.CycloramaConfigurationActionBean.java

private String getBase64EncodedPrivateKeyFromPfxUpload(InputStream in, String password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {

    String base64 = null;/* w w w.j  a v  a2s .c  om*/

    PrivateKey privateKey = null;

    KeyStore ks = java.security.KeyStore.getInstance(CERT_TYPE);
    ks.load(new BufferedInputStream(in), password.toCharArray());

    Enumeration<String> aliases = ks.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        Key ksKey = ks.getKey(alias, password.toCharArray());
        String keyFormat = ksKey.getFormat();

        if ((ksKey instanceof RSAPrivateCrtKeyImpl) && keyFormat.equals(KEY_FORMAT)) {
            privateKey = (PrivateKey) ksKey;
        }
    }

    if (privateKey != null) {
        Base64 encoder = new Base64();
        base64 = new String(encoder.encode(privateKey.getEncoded()));
    }

    return base64;
}

From source file:org.codice.ddf.admin.insecure.defaults.service.KeystoreValidator.java

private void validateKeyPasswords(KeyStore keystore) {
    try {/*from  ww  w .jav a  2s. c o  m*/
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            if (keystore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)
                    || keystore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
                if (StringUtils.isNotBlank(defaultKeyPassword)) {
                    // See if we can access the key using the default key password. If we
                    // cannot, we
                    // know that we are using a non-default password.
                    Key key = keystore.getKey(alias, defaultKeyPassword.toCharArray());
                    if (key != null) {
                        alerts.add(new Alert(Level.WARN, String.format(DEFAULT_KEY_PASSWORD_USED_MSG, alias,
                                keystorePath, defaultKeyPassword)));
                    }
                } else {
                    alerts.add(new Alert(Level.WARN, String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath)
                            + "No key password provided."));
                }
            }
        }
    } catch (UnrecoverableKeyException e) {
        // Key is not using default key password.
    } catch (KeyStoreException | NoSuchAlgorithmException e) {
        LOGGER.warn(String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath), e);
        alerts.add(new Alert(Level.WARN,
                String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath) + e.getMessage() + "."));
    }
}

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

/**
 * @throws java.lang.Exception//from  w ww .ja va  2  s. co m
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    // Just in case, add the BouncyCastle provider
    // It gets added from the CredentialManagerImpl constructor as well
    // but we may need some crypto operations before we invoke the Cred. Manager 
    Security.addProvider(new BouncyCastleProvider());

    // Create a test username and password for a service
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
}

From source file:davmail.util.ClientCertificateTest.java

public void testWindowsSmartCard() {
    try {//w  w w .  ja v  a2  s . c  o  m
        KeyStore ks = KeyStore.getInstance("Windows-MY");
        ks.load(null, null);
        java.util.Enumeration en = ks.aliases();

        while (en.hasMoreElements()) {
            String aliasKey = (String) en.nextElement();
            X509Certificate c = (X509Certificate) ks.getCertificate(aliasKey);
            System.out.println("---> alias : " + aliasKey + " " + c.getSubjectDN());

            //PrivateKey key = (PrivateKey) ks.getKey(aliasKey, "Passw0rd".toCharArray());
            Certificate[] chain = ks.getCertificateChain(aliasKey);
        }

    } catch (Exception ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:com.streamsets.datacollector.credential.javakeystore.JavaKeyStoreCredentialStore.java

public List<String> getAliases() {
    List<String> aliases = new ArrayList<>();
    try {//from  www . j  a  v a 2s.  com
        KeyStore keyStore = loadKeyStore();
        if (keyStore != null) {
            Enumeration<String> it = keyStore.aliases();
            while (it.hasMoreElements()) {
                aliases.add(it.nextElement());
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    return aliases;
}

From source file:io.pivotal.springcloud.ssl.CloudFoundryCertificateTruster.java

/**
 * import trust from truststore file// w ww .  ja  v a2s.c  om
 *
 * @param applicationContext
 * @param trustStore
 * @param trustStorePassword
 */
private void trustCertificatesFromStoreInternal(ConfigurableApplicationContext applicationContext,
        String trustStore, String trustStorePassword) {
    if (trustStore != null) {
        try {
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(applicationContext.getResource(trustStore).getInputStream(),
                    trustStorePassword.toCharArray());
            Enumeration<String> aliases = keystore.aliases();

            List<X509Certificate> certCollect = new ArrayList<X509Certificate>();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();

                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null && certs.length > 0)
                    for (Certificate cert : certs)
                        if (cert instanceof X509Certificate)
                            certCollect.add((X509Certificate) cert);

                Certificate cert = keystore.getCertificate(alias);
                if (cert != null && cert instanceof X509Certificate) {
                    certCollect.add((X509Certificate) cert);
                }
            }

            if (certCollect.size() > 0)
                sslCertificateTruster.appendToTruststoreInternal(certCollect.toArray(new X509Certificate[0]));

        } catch (Exception e) {
            log.error("trusting trustore at {}:{} failed", trustStore, trustStorePassword, e);
        }
    }
}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Lists keystore contents on STDOUT. Output is similar to keytool -list -v.
 *
 * @param  line  Parsed command line arguments container.
 *
 * @throws  Exception  On errors./*from ww  w.  j ava 2s. c  om*/
 */
protected void list(final CommandLine line) throws Exception {
    validateOptions(line);

    final KeyStore store = readKeyStore(line);
    final Enumeration<String> aliases = store.aliases();
    System.out.println("");
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        System.out.println("Alias name: " + alias);
        System.out.println("Creation date: " + store.getCreationDate(alias));
        if (store.isKeyEntry(alias)) {
            System.out.println("Entry type: keyEntry");

            final Certificate[] chain = store.getCertificateChain(alias);
            System.out.println("Certificate chain length: " + chain.length);
            for (int i = 0; i < chain.length; i++) {
                System.out.println("===== Certificate [" + i + "] =====");
                printCertificate(chain[i]);
            }
        } else {
            System.out.println("Entry type: trustedCertEntry");
            System.out.println("Certificate details:");
            printCertificate(store.getCertificate(alias));
        }
        System.out.println("");
        System.out.println("");
    }
}

From source file:mitm.common.tools.PfxTool.java

private void mergePfx() throws Exception {
    if (StringUtils.isEmpty(destFile)) {
        throw new MissingOptionException(destOption.getOpt() + " is missing.");
    }//from w w w . ja  v  a  2s .  co m

    if (StringUtils.isEmpty(destPassword)) {
        throw new MissingOptionException(destPasswordOption.getOpt() + " is missing.");
    }

    KeyStore inStore = loadKeyStore(inFile, true, inPassword);
    KeyStore destStore = loadKeyStore(destFile, false, destPassword);

    Enumeration<String> aliases = inStore.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        String destAlias = retainAliases ? alias : UUID.randomUUID().toString() + "_" + alias;

        if (inStore.isKeyEntry(alias)) {
            KeyStore.Entry entry = inStore.getEntry(alias,
                    new KeyStore.PasswordProtection(inPassword.toCharArray()));

            destStore.setEntry(destAlias, entry, new KeyStore.PasswordProtection(destPassword.toCharArray()));
        } else {
            Certificate certificate = inStore.getCertificate(alias);

            destStore.setCertificateEntry(destAlias, certificate);
        }
    }

    destStore.store(new FileOutputStream(destFile), destPassword.toCharArray());
}