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:org.teknux.jettybootstrap.keystore.JettyKeystoreConvertorBuilder.java

private static PrivateKeyEntry getPrivateKeyEntryOfKeyStore(KeyStore keystore, String password, String alias)
        throws JettyKeystoreException {
    try {// w ww  . j  av a2  s .  c o  m
        if (alias == null) {
            Enumeration<String> aliasEnumeration = keystore.aliases();

            while (aliasEnumeration.hasMoreElements()) {
                String aliasItem = aliasEnumeration.nextElement();

                if (keystore.isKeyEntry(aliasItem)) {
                    Entry entry = keystore.getEntry(aliasItem,
                            new KeyStore.PasswordProtection(password.toCharArray()));

                    if (entry instanceof PrivateKeyEntry) {
                        return (PrivateKeyEntry) entry;
                    }
                }
            }

        } else {
            Entry entry = keystore.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));

            if (entry instanceof PrivateKeyEntry) {
                return (PrivateKeyEntry) entry;
            }
        }

        throw new JettyKeystoreException(JettyKeystoreException.ERROR_UNREACHABLE_PRIVATE_KEY_ENTRY,
                "Can not find private key entry");
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_UNREACHABLE_PRIVATE_KEY_ENTRY,
                "Can not find private key entry", e);
    }
}

From source file:org.dasein.cloud.google.GenerateToken.java

public static String getToken(String iss, String p12File) {

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    String claimTemplate = "'{'\"iss\": \"{0}\", \"scope\": \"{1}\", \"aud\": \"{2}\", \"exp\": \"{3}\", \"iat\": \"{4}\"'}'";

    try {/*from  ww  w.  jav a 2s  .  co  m*/
        StringBuffer token = new StringBuffer();

        //Encode the JWT Header and add it to our string to sign
        token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

        //Separate with a period
        token.append(".");

        //Create the JWT Claims Object
        String[] claimArray = new String[5];
        claimArray[0] = iss;
        claimArray[1] = "https://www.googleapis.com/auth/compute";
        claimArray[2] = "https://accounts.google.com/o/oauth2/token";
        claimArray[3] = Long.toString((System.currentTimeMillis() / 1000) + 300);
        claimArray[4] = Long.toString((System.currentTimeMillis() / 1000));
        MessageFormat claims;
        claims = new MessageFormat(claimTemplate);
        String payload = claims.format(claimArray);
        //         System.out.println(claimArray[3]);
        //         System.out.println(claimArray[4]);
        //Add the encoded claims object
        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        char[] password = "notasecret".toCharArray();
        FileInputStream fin = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(fin, password);
        } finally {
            try {
                fin.close();
            } catch (IOException e) {
            }
        }
        String alias = "";
        // KeyStore keystore = getKeyStore(password);            
        Enumeration<String> enum1 = store.aliases(); // List the aliases
        while (enum1.hasMoreElements()) {
            String keyStoreAlias = enum1.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) { //Does alias refer to a private key?
                alias = keyStoreAlias;
                break;
            }
        }
        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        //Sign the JWT Header + "." + JWT Claims Object
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(token.toString().getBytes("UTF-8"));
        String signedPayload = Base64.encodeBase64URLSafeString(signature.sign());

        //Separate with a period
        token.append(".");

        //Add the encoded signature
        token.append(signedPayload);

        //      System.out.println(token.toString());
        return token.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.link.util.common.KeyUtils.java

public static ImmutableMap<String, X509Certificate> getCertificates(KeyStore keyStore,
        Predicate<String> ignoreAlias) {

    Enumeration<String> aliases;
    try {/* ww  w .jav a  2  s  .co  m*/
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("could not enumerate aliases", e);
    }

    ImmutableMap.Builder<String, X509Certificate> certificates = ImmutableMap.builder();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (ignoreAlias != null && ignoreAlias.apply(alias))
            continue;

        try {
            if (keyStore.isCertificateEntry(alias))
                certificates.put(alias, (X509Certificate) keyStore.getCertificate(alias));
        } catch (KeyStoreException e) {
            throw new InternalInconsistencyException(
                    String.format("error retrieving certificate, alias=%s", alias), e);
        }
    }

    return certificates.build();
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

public static PKSigningInformation loadSigningInformationFromPKCS12FileAndIntermediateCertificateFile(
        final String pkcs12KeyStoreFilePath, final String keyStorePassword, final String appleWWDRCAFilePath)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        NoSuchProviderException, UnrecoverableKeyException {
    addBCProvider();/*from w  w  w.  j  a v a  2  s  .c  o  m*/

    KeyStore pkcs12KeyStore = loadPKCS12File(pkcs12KeyStoreFilePath, keyStorePassword);
    Enumeration<String> aliases = pkcs12KeyStore.aliases();

    PrivateKey signingPrivateKey = null;
    X509Certificate signingCert = null;

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

        Key key = pkcs12KeyStore.getKey(aliasName, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            signingPrivateKey = (PrivateKey) key;
            Object cert = pkcs12KeyStore.getCertificate(aliasName);
            if (cert instanceof X509Certificate) {
                signingCert = (X509Certificate) cert;
                break;
            }
        }
    }

    X509Certificate appleWWDRCACert = loadDERCertificate(appleWWDRCAFilePath);
    if (signingCert == null || signingPrivateKey == null || appleWWDRCACert == null) {
        throw new IOException("Couldn#t load all the neccessary certificates/keys");
    }

    return new PKSigningInformation(signingCert, signingPrivateKey, appleWWDRCACert);
}

From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java

/**
 * Does the supplied KeyStore contain any key entries? ie any entries that
 * contain a key with no certificate chain.
 *
 * @param keyStore//from ww w  .  java2 s .  c  o m
 *            KeyStore
 * @return True if it does
 * @throws CryptoException
 *             Problem occurred checking the KeyStore
 */
public static boolean containsKey(KeyStore keyStore) throws CryptoException {
    try {
        Enumeration<String> aliases = keyStore.aliases();

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

            if (isKeyEntry(alias, keyStore)) {
                return true;
            }
        }

        return false;
    } catch (KeyStoreException ex) {
        throw new CryptoException(res.getString("NoCheckKeyStoreKeys.exception.message"), ex);
    }
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

/**
 * Load all signing information necessary for pass generation using two input streams for the key store and the Apple WWDRCA certificate.
 * //from   ww w.ja  v a 2 s.  c om
 * The caller is responsible for closing the stream after this method returns successfully or fails.
 * 
 * @param pkcs12KeyStoreInputStream
 *            <code>InputStream</code> of the key store
 * @param keyStorePassword
 *            Password used to access the key store
 * @param appleWWDRCAFileInputStream
 *            <code>InputStream</code> of the Apple WWDRCA certificate.
 * @return Signing informatino necessary to sign a pass.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws UnrecoverableKeyException
 */
public static PKSigningInformation loadSigningInformationFromPKCS12AndIntermediateCertificateStreams(
        final InputStream pkcs12KeyStoreInputStream, final String keyStorePassword,
        final InputStream appleWWDRCAFileInputStream) throws IOException, NoSuchAlgorithmException,
        CertificateException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException {
    addBCProvider();

    KeyStore pkcs12KeyStore = loadPKCS12File(pkcs12KeyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases = pkcs12KeyStore.aliases();

    PrivateKey signingPrivateKey = null;
    X509Certificate signingCert = null;

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

        Key key = pkcs12KeyStore.getKey(aliasName, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            signingPrivateKey = (PrivateKey) key;
            Object cert = pkcs12KeyStore.getCertificate(aliasName);
            if (cert instanceof X509Certificate) {
                signingCert = (X509Certificate) cert;
                break;
            }
        }
    }

    X509Certificate appleWWDRCACert = loadDERCertificate(appleWWDRCAFileInputStream);
    if (signingCert == null || signingPrivateKey == null || appleWWDRCACert == null) {
        throw new IOException("Couldn#t load all the neccessary certificates/keys");
    }

    return new PKSigningInformation(signingCert, signingPrivateKey, appleWWDRCACert);
}

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

private static void printKeystoreAliases(KeyStore keyStore) throws KeyStoreException {
    Enumeration<String> aliases = keyStore.aliases();

    System.out.println("**** BEGIN KEY ALIASES ***");

    while (aliases.hasMoreElements()) {
        System.out.println(aliases.nextElement());
    }/*  w w w. j  a va2 s . com*/

    System.out.println("**** END KEY ALIASES ***");
}

From source file:net.link.util.common.KeyUtils.java

public static PrivateKeyEntry loadPrivateKeyEntry(String keystoreType, InputStream keyStoreInputStream,
        char[] keyStorePassword, char[] keyEntryPassword, String alias) {

    /* Find the keystore. */
    KeyStore keyStore = loadKeyStore(keystoreType, keyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases;
    try {//from  w  w  w.j  a v a2  s . c  om
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("could not get aliases", e);
    }
    if (!aliases.hasMoreElements())
        throw new InternalInconsistencyException("keystore is empty");

    try {
        if (!keyStore.isKeyEntry(alias))
            throw new InternalInconsistencyException(String.format("not key entry: %s", alias));
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("key store error", e);
    }

    /* Get the private key entry. */
    try {
        return (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(keyEntryPassword));
    } catch (UnrecoverableEntryException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    }
}

From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java

protected static KeyStore createKeyStore(final URL url, final String password, String keyStoreType,
        String prefix) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url for " + prefix + " may not be null");
    }/*from   w w w.  j  a  va  2 s.  c  om*/
    log.info("Initializing keystore for " + prefix + " from " + url.toString());
    KeyStore keystore = KeyStore.getInstance(keyStoreType);
    keystore.load(url.openStream(), password != null ? password.toCharArray() : null);
    if (log.isInfoEnabled()) {
        Enumeration aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            log.info(prefix + " '" + alias + "':");
            Certificate trustedcert = keystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                log.info("  Subject DN: " + cert.getSubjectDN());
                log.info("  Signature Algorithm: " + cert.getSigAlgName());
                log.info("  Valid from: " + cert.getNotBefore());
                log.info("  Valid until: " + cert.getNotAfter());
                log.info("  Issuer: " + cert.getIssuerDN());
            }
        }
    }
    return keystore;
}

From source file:net.link.util.common.KeyUtils.java

public static PrivateKeyEntry loadFirstPrivateKeyEntry(String keystoreType, InputStream keyStoreInputStream,
        char[] keyStorePassword, char[] keyEntryPassword) {

    /* Find the keystore. */
    KeyStore keyStore = loadKeyStore(keystoreType, keyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases;
    try {//  w  w  w.  j  a v  a 2 s  .c  om
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("could not get aliases", e);
    }
    String alias = null;
    while (aliases.hasMoreElements()) {
        alias = aliases.nextElement();
        try {
            if (keyStore.isKeyEntry(alias))
                break;
        } catch (KeyStoreException e) {
            throw new InternalInconsistencyException(e);
        }

        alias = null;
    }
    if (alias == null)
        throw new InternalInconsistencyException("no private key found in keystore");

    /* Get the private key entry. */
    try {
        return (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(keyEntryPassword));
    } catch (UnrecoverableEntryException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    }
}