Example usage for java.security KeyStore getCertificateChain

List of usage examples for java.security KeyStore getCertificateChain

Introduction

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

Prototype

public final Certificate[] getCertificateChain(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate chain associated with the given alias.

Usage

From source file:it.cnr.icar.eric.common.security.KeystoreMover.java

public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword,
        String sourceAlias, String sourceKeyPassword, String destinationKeystoreType,
        String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias,
        String destinationKeyPassword) throws Exception {

    char[] sourceKeystorePasswordArr = null;
    if (sourceKeystorePassword != null) {
        sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray();
    }/* w  ww.  j  a  v a  2 s .c  om*/

    char[] sourceKeyPasswordArr = sourceKeystorePasswordArr;
    if (sourceKeyPassword != null) {
        sourceKeyPasswordArr = sourceKeyPassword.toCharArray();
    }

    char[] destinationKeystorePasswordArr = null;
    if (destinationKeystorePassword != null) {
        destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray();
    }

    char[] destinationKeyPasswordArr = destinationKeystorePasswordArr;
    if (destinationKeyPassword != null) {
        destinationKeyPasswordArr = destinationKeyPassword.toCharArray();
    }

    FileInputStream in;

    // --------  Load source keystore to memory ---------
    in = new FileInputStream(sourceKeystorePath);
    KeyStore ksin = KeyStore.getInstance(sourceKeystoreType);

    ksin.load(in, sourceKeystorePasswordArr);
    in.close();

    // --------  Load destination keystore initial contents to memory ---------
    KeyStore ksout = KeyStore.getInstance(destinationKeystoreType);

    try {
        in = new FileInputStream(destinationKeystorePath);
        ksout.load(in, destinationKeystorePasswordArr);
    } catch (java.io.FileNotFoundException e) {
        ksout.load(null, destinationKeystorePasswordArr);
    } finally {
        in.close();
    }

    Enumeration<String> en = ksin.aliases();
    while (en.hasMoreElements()) {
        String alias = en.nextElement();

        if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) {

            if (ksout.containsAlias(alias)) {
                log.info(CommonResourceBundle.getInstance().getString(
                        "message.destinationKeystorePathAlreadyContains",
                        new Object[] { destinationKeystorePath, alias }));
                continue;
            }

            //Use existing alias if no destinationAlias specified
            if (destinationAlias == null) {
                destinationAlias = alias;
            }

            if (ksin.isCertificateEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate",
                        new Object[] { alias }));
                ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias));
            }

            if (ksin.isKeyEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingKey",
                        new Object[] { alias }));
                Certificate[] certChain = ksin.getCertificateChain(alias);
                ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr),
                        destinationKeyPasswordArr, certChain);
            }
        }

    }

    //---------  Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores--------------
    FileOutputStream out = new FileOutputStream(destinationKeystorePath);
    ksout.store(out, destinationKeystorePasswordArr);
    out.close();
    log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful"));
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

protected KeyMap cacheKeys(KeyStore ks, KeyInfoManager keyInfoManager)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    KeyMap keys = new KeyMap();

    // load and cache the keys
    for (Entry<String, KeyInformation> keyEntry : keyInfoManager.getKeyInfo().entrySet()) {
        String keyAlias = keyEntry.getKey();

        KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias);
        String passwordStr = keyInfo != null ? keyInfo.getPassword() : null;

        // Null is an acceptable value (means no key)
        Key key = null;//w  ww . ja  va2  s.  c o  m

        // Attempt to get the key
        key = ks.getKey(keyAlias, passwordStr == null ? null : passwordStr.toCharArray());
        if (key != null) {
            keys.setKey(keyAlias, key);
        }
        // Key loaded
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Retrieved key from keystore: \n" + "   Location: " + getKeyStoreParameters().getLocation()
                            + "\n" + "   Provider: " + getKeyStoreParameters().getProvider() + "\n"
                            + "   Type:     " + getKeyStoreParameters().getType() + "\n" + "   Alias:    "
                            + keyAlias + "\n" + "   Password?: " + (passwordStr != null));

            Certificate[] certs = ks.getCertificateChain(keyAlias);
            if (certs != null) {
                logger.debug("Certificate chain '" + keyAlias + "':");
                for (int c = 0; c < certs.length; c++) {
                    if (certs[c] instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) certs[c];
                        logger.debug(" Certificate " + (c + 1) + ":");
                        logger.debug("  Subject DN: " + cert.getSubjectDN());
                        logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        logger.debug("  Valid from: " + cert.getNotBefore());
                        logger.debug("  Valid until: " + cert.getNotAfter());
                        logger.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
        }
    }

    return keys;
}

From source file:org.tolven.config.model.CredentialManager.java

public void changeGroupCredentialPassword(PasswordInfo passwordInfo, char[] oldPassword, char[] newPassword)
        throws IOException, GeneralSecurityException {
    if (oldPassword == null)
        throw new RuntimeException("Old password '" + passwordInfo.getRefId() + "' is null");
    if (!getPasswordHolder().verify(passwordInfo, oldPassword))
        throw new RuntimeException("Old Password is invalid for '" + passwordInfo.getRefId() + "'");
    if (newPassword == null)
        throw new RuntimeException("New password '" + passwordInfo.getRefId() + "' is null");
    CertificateGroupDetail certGroup = getTolvenConfigWrapper().getCredentialGroup(passwordInfo.getRefId());
    CertificateKeyDetail keyDetail = certGroup.getKey();
    PrivateKey privateKey = getPrivateKey(keyDetail, oldPassword);
    File keyFile = new File(keyDetail.getSource());
    KeyStore keyStore = null;
    File keyStoreFile = null;/*from ww w  . ja  v  a 2  s . c o m*/
    CertificateKeyStoreDetail certKeyStoreDetail = certGroup.getKeyStore();
    if (certKeyStoreDetail != null) {
        keyStore = getTolvenConfigWrapper().getKeyStore(oldPassword, certKeyStoreDetail);
        keyStoreFile = new File(certKeyStoreDetail.getSource());
    }
    TrustStoreDetail trustStoreDetail = getTolvenConfigWrapper().getTrustStoreDetail(passwordInfo.getRefId());
    KeyStore trustStore = null;
    File trustStoreFile = null;
    if (trustStore != null) {
        trustStore = getTolvenConfigWrapper().getTrustStore(oldPassword, trustStoreDetail);
        trustStoreFile = new File(trustStoreDetail.getSource());
    }
    File tmpKey = null;
    File tmpKeyStore = null;
    File tmpTrustStore = null;
    boolean success = false;
    try {
        getTolvenConfigWrapper().getBuildDir().mkdirs();
        tmpKey = new File(getTolvenConfigWrapper().getBuildDir(), keyFile.getName());
        write(privateKey, keyDetail.getFormat(), tmpKey, newPassword);
        if (keyStoreFile != null) {
            tmpKeyStore = new File(getTolvenConfigWrapper().getBuildDir(), keyStoreFile.getName());
            String alias = keyStore.aliases().nextElement();
            Key key = keyStore.getKey(alias, oldPassword);
            Certificate[] chain = keyStore.getCertificateChain(alias);
            keyStore.setKeyEntry(alias, key, newPassword, chain);
            write(keyStore, tmpKeyStore, newPassword);
        }
        if (trustStoreFile != null) {
            tmpTrustStore = new File(getTolvenConfigWrapper().getBuildDir(), trustStoreFile.getName());
            write(trustStore, tmpTrustStore, newPassword);
        }
        FileUtils.copyFile(tmpKey, keyFile);
        if (keyStoreFile != null) {
            FileUtils.copyFile(tmpKeyStore, keyStoreFile);
        }
        if (trustStoreFile != null) {
            FileUtils.copyFile(tmpTrustStore, trustStoreFile);
        }
        success = true;
    } finally {
        if (success) {
            if (tmpKey != null) {
                tmpKey.delete();
            }
            if (tmpKeyStore != null) {
                tmpKeyStore.delete();
            }
            if (tmpKeyStore != null) {
                tmpKeyStore.delete();
            }
            getPasswordHolder().changePassword(passwordInfo, oldPassword, newPassword);
        }
    }
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

/** Create InternalKeyBindings for Ocsp signing and SSL client authentication certs during ad-hoc upgrades. */
@Deprecated //Remove this method as soon as upgrading from 5->6 is dropped
private void createInternalKeyBindings(AuthenticationToken authenticationToken, int cryptoTokenId,
        KeyStore keyStore, List<InternalKeyBindingTrustEntry> trustDefaults) throws KeyStoreException,
        CryptoTokenOfflineException, InternalKeyBindingNameInUseException, AuthorizationDeniedException,
        CertificateEncodingException, CertificateImportException, InvalidAlgorithmException {
    final Enumeration<String> aliases = keyStore.aliases();
    boolean noAliases = true;
    while (aliases.hasMoreElements()) {
        final String keyPairAlias = aliases.nextElement();
        noAliases = false;//from   w  ww  . j av  a2 s.  co m
        log.info("Found alias " + keyPairAlias
                + ", trying to figure out if this is something we should convert into a new KeyBinding...");
        final Certificate[] chain = keyStore.getCertificateChain(keyPairAlias);
        if (chain == null || chain.length == 0) {
            log.info("Alias " + keyPairAlias + " does not contain any certificate and will be ignored.");
            continue; // Ignore entry
        }
        // Extract the default signature algorithm
        final String signatureAlgorithm = getSigningAlgFromAlgSelection(
                OcspConfiguration.getSignatureAlgorithm(), chain[0].getPublicKey());
        if (OcspKeyBinding.isOcspSigningCertificate(chain[0])) {
            // Create the actual OcspKeyBinding
            log.info("Alias " + keyPairAlias
                    + " contains an OCSP certificate and will be converted to an OcspKeyBinding.");
            int internalKeyBindingId = internalKeyBindingMgmtSession.createInternalKeyBinding(
                    authenticationToken, OcspKeyBinding.IMPLEMENTATION_ALIAS,
                    "OcspKeyBinding for " + keyPairAlias, InternalKeyBindingStatus.DISABLED, null,
                    cryptoTokenId, keyPairAlias, signatureAlgorithm, getOcspKeyBindingDefaultProperties(),
                    trustDefaults);
            internalKeyBindingMgmtSession.importCertificateForInternalKeyBinding(authenticationToken,
                    internalKeyBindingId, chain[0].getEncoded());
            internalKeyBindingMgmtSession.setStatus(authenticationToken, internalKeyBindingId,
                    InternalKeyBindingStatus.ACTIVE);
        } else if (AuthenticationKeyBinding.isClientSSLCertificate(chain[0])) {
            log.info("Alias " + keyPairAlias
                    + " contains an SSL client certificate and will be converted to an AuthenticationKeyBinding.");
            // We are looking for an SSL cert, use this to create an AuthenticationKeyBinding
            int internalKeyBindingId = internalKeyBindingMgmtSession.createInternalKeyBinding(
                    authenticationToken, AuthenticationKeyBinding.IMPLEMENTATION_ALIAS,
                    "AuthenticationKeyBinding for " + keyPairAlias, InternalKeyBindingStatus.DISABLED, null,
                    cryptoTokenId, keyPairAlias, signatureAlgorithm, null, null);
            internalKeyBindingMgmtSession.importCertificateForInternalKeyBinding(authenticationToken,
                    internalKeyBindingId, chain[0].getEncoded());
            internalKeyBindingMgmtSession.setStatus(authenticationToken, internalKeyBindingId,
                    InternalKeyBindingStatus.ACTIVE);
        } else {
            log.info("Alias " + keyPairAlias + " contains certificate of unknown type and will be ignored.");
        }
    }
    if (noAliases) {
        log.info("No aliases to process were found in the key store.");
    }
}

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

private List<X509Certificate> getSTSKeyCertificates() throws Exception {
    Properties props = getTestProperties();
    KeyStore ks = loadKeyStore(CFG_KEY_STS_KEYSTORE, CFG_KEY_STS_KEYSTORE_PASSWORD);
    Certificate[] certChain = ks.getCertificateChain(props.getProperty(CFG_KEY_STS_KEY_ALIAS));
    List<X509Certificate> x509Certs = new ArrayList<X509Certificate>();
    for (Certificate cert : certChain) {
        x509Certs.add((X509Certificate) cert);
    }/*from  w ww  .  j  av a2 s.  c  om*/
    return x509Certs;
}