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:au.edu.monash.merc.capture.util.httpclient.ssl.AuthSSLProtocolSocketFactory.java

@SuppressWarnings("rawtypes")
private SSLContext createSSLContext() {
    try {/*from   w  w  w  .j  a v a 2  s. c  o  m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:eu.europa.ec.markt.dss.signature.token.Pkcs12SignatureToken.java

@Override
public List<DSSPrivateKeyEntry> getKeys() throws KeyStoreException {

    List<DSSPrivateKeyEntry> list = new ArrayList<DSSPrivateKeyEntry>();

    InputStream input = null;//  w w w  .j  a v a 2s  . co  m
    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        if (pkcs12Data != null) {
            input = new ByteArrayInputStream(pkcs12Data);
        } else {
            input = new FileInputStream(pkcs12File);
        }

        keyStore.load(input, password);
        PasswordProtection pp = new KeyStore.PasswordProtection(password);
        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {

            String alias = aliases.nextElement();
            if (keyStore.isKeyEntry(alias)) {

                PrivateKeyEntry entry = (PrivateKeyEntry) keyStore.getEntry(alias, pp);
                list.add(new KSPrivateKeyEntry(entry));
            }
        }
    } catch (Exception e) {
        if (e.getCause() instanceof BadPaddingException) {
            throw new BadPasswordException(MSG.PKCS12_BAD_PASSWORD);
        }
        throw new KeyStoreException(
                "Can't initialize Sun PKCS#12 security provider. Reason: " + getCauseMessage(e), e);
    } finally {
        DSSUtils.closeQuietly(input);
    }
    return list;
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

/**
 * //w  w w  .  jav  a 2  s  . c o  m
 * @param keystoreName
 * @param keystore
 * @throws KeyStoreException
 */
private void logKeystoreContents(String keystoreName, KeyStore keystore) throws KeyStoreException {
    Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Keystore : '" + keystoreName + "':");
    for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) {
        String alias = (String) aliases.nextElement();
        Certificate[] certs = keystore.getCertificateChain(alias);
        if (certs != null) {
            Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Certificate Chain '" + alias + "':");
            for (Certificate cert : certs)
                logCertificateContents(cert);
        } else {
            Certificate cert = keystore.getCertificate(alias);
            Logger.getLogger(AuthSSLProtocolSocketFactory.class)
                    .debug("Trusted Certificate Authority '" + alias + "':");
            logCertificateContents(cert);
        }
    }
}

From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*ww  w  .j a v  a  2s.  c o  m*/
        // KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        /*
        if (this.keystoreUrl != null) {
        KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
        if (LOG.isDebugEnabled()) {
            Enumeration aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String)aliases.nextElement();
                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null) {
                    LOG.debug("Certificate chain '" + alias + "':");
                    for (int c = 0; c < certs.length; c++) {
                        if (certs[c] instanceof X509Certificate) {
                            X509Certificate cert = (X509Certificate)certs[c];
                            LOG.debug(" Certificate " + (c + 1) + ":");
                            LOG.debug("  Subject DN: " + cert.getSubjectDN());
                            LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                            LOG.debug("  Valid from: " + cert.getNotBefore() );
                            LOG.debug("  Valid until: " + cert.getNotAfter());
                            LOG.debug("  Issuer: " + cert.getIssuerDN());
                        }
                    }
                }
            }
        }
        keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        */
        if (this.truststoreUrls != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrls, this.truststorePasswords);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(null, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from ww w  .j av a 2 s  .  c om
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSLv3");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException(
                "I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testAliasesAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate// www  . j  a  va  2 s.c om
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            // "https://www.e-contract.be/hsm-proxy-ws/dss",
            "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    hsmProxyKeyStore.load(keyStoreParameter);

    Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases();
    assertNotNull(aliasesEnum);
    while (aliasesEnum.hasMoreElements()) {
        LOG.debug("alias: " + aliasesEnum.nextElement());
    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 *
 * @param keystore/*w  w  w.  java 2  s  .  c o  m*/
 * @param serialNumber
 * @param issuer
 * @return a certificate/alias pair from the keystore, having the given issuer and serialNumber
 * @throws KeyStoreException
 * @throws SAMLEngineException
 */
public static CertificateAliasPair getCertificatePair(KeyStore keystore, String serialNumber, String issuer)
        throws KeyStoreException, SAMLEngineException {
    String alias = null;
    String aliasCert;
    X509Certificate certificate;
    boolean find = false;
    LOG.debug("cherche dans " + keystore.toString() + " numSerie=" + serialNumber + " issuer=" + issuer);
    for (final Enumeration<String> e = keystore.aliases(); e.hasMoreElements() && !find;) {
        aliasCert = e.nextElement();
        certificate = (X509Certificate) keystore.getCertificate(aliasCert);

        final String serialNum = certificate.getSerialNumber().toString(16);

        Principal p = certificate.getIssuerDN();
        String name = p.getName();

        X500Name issuerDN = new X500Name(name);
        X500Name issuerDNConf = new X500Name(issuer);

        if (serialNum.equalsIgnoreCase(serialNumber)
                && X500PrincipalUtil.principalEquals(issuerDN, issuerDNConf)) {
            alias = aliasCert;
            find = true;
        } else {
            LOG.debug("pas pareil numSerie=" + serialNum + " ou issuer=" + name);
        }
    }
    if (!find) {
        throw new SAMLEngineException(
                "Certificate " + issuer + "/" + serialNumber + " cannot be found in keystore ");
    }
    certificate = (X509Certificate) keystore.getCertificate(alias);
    return new CertificateAliasPair(certificate, alias);

}

From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java

@Override
public List<String> list() {
    // List of issuer distinguished name
    final List<String> list = new ArrayList<String>();
    try {//w  w w. ja  v a2s.  c o m
        final KeyStore store;
        try {
            store = this.getKeystore();
        } catch (IOException e) {
            log.warn(String.format("Failure listing aliases. %s", e.getMessage()));
            return Collections.emptyList();
        }
        final Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            final String alias = aliases.nextElement();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Alias in Keychain %s", alias));
            }
            if (store.isKeyEntry(alias)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Found private key for %s", alias));
                }
                list.add(alias);
            } else {
                log.warn(String.format("Missing private key for alias %s", alias));
            }
        }
    } catch (KeyStoreException e) {
        log.error(String.format("Keystore not loaded %s", e.getMessage()));
    }
    return list;
}

From source file:org.objectweb.proactive.extensions.ssl.KeyStoreCreator.java

private boolean verify(String keyStore) {
    // Load the keystore
    FileInputStream fis = null;//from  w  w  w  . ja  v  a2 s.c  om
    try {
        fis = new FileInputStream(keyStore);
    } catch (FileNotFoundException e) {
        System.err.println("Failed to open the key store: " + e);
        return false;
    }

    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("PKCS12", SslHelpers.BC_NAME);
        ks.load(fis, SslHelpers.DEFAULT_KS_PASSWD.toCharArray());
    } catch (Exception e) {
        System.err.println("Failed to open the key store: " + e);
        return false;
    }

    try {

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

        List<Certificate> matchingCerts = new LinkedList<Certificate>();
        List<Certificate> otherCerts = new LinkedList<Certificate>();

        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            //                if (ks.isCertificateEntry(alias)) {
            if (alias.matches(SslHelpers.DEFAULT_ALIAS_PATTERN)) {
                matchingCerts.add(ks.getCertificate(alias));
            } else {
                otherCerts.add(ks.getCertificate(alias));
            }
            //                }

            if (matchingCerts.size() > 0) {
                System.out.println(matchingCerts.size() + " matching certificate found");
                for (Certificate cert : matchingCerts) {
                    System.out.println(cert);
                }
            } else {
                System.err.println("No matching certificate foud. " + otherCerts.size()
                        + " non matching certificate found.");
                return false;
            }
        }
    } catch (KeyStoreException e) {
        // Should not happen. Only throwed if the keystore is not initialized
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:de.betterform.connector.http.ssl.BetterFORMKeyStoreManager.java

private X509KeyManager getCustomX509KeyManager(final URL url, final String password)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (url == null) {
        throw new IllegalArgumentException("BetterFORMKeyStoreManager: Keystore url may not be null");
    }/* w w  w. j a v a  2s .c om*/

    LOGGER.debug("BetterFORMKeyStoreManager: initializing custom key store");
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = null;
    try {
        is = url.openStream();
        customKeystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }

    if (LOGGER.isTraceEnabled()) {
        Enumeration aliases = customKeystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            LOGGER.trace("Trusted certificate '" + alias + "':");
            Certificate trustedcert = customKeystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                LOGGER.trace("  Subject DN: " + cert.getSubjectDN());
                LOGGER.trace("  Signature Algorithm: " + cert.getSigAlgName());
                LOGGER.trace("  Valid from: " + cert.getNotBefore());
                LOGGER.trace("  Valid until: " + cert.getNotAfter());
                LOGGER.trace("  Issuer: " + cert.getIssuerDN());
            }
        }
    }
    keyManagerFactory.init(customKeystore, password.toCharArray());

    KeyManager[] customX509KeyManagers = keyManagerFactory.getKeyManagers();
    if (customX509KeyManagers != null && customX509KeyManagers.length > 0) {
        for (int i = 0; i < customX509KeyManagers.length; i++) {
            if (customX509KeyManagers[i] instanceof X509KeyManager) {
                return (X509KeyManager) customX509KeyManagers[i];
            }
        }
    }

    return null;
}