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:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#loadPKCS12Keystore(java.io.File, java.lang.String)}.
 * @throws CMException //from  w w  w.  j a v  a2  s.  co  m
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testLoadPKCS12Keystore()
        throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(new File(privateKeyFileURL.getPath()),
            privateKeyAndPKCS12KeystorePassword);

    Key privateKey2 = null;
    Certificate[] privateKeyCertChain2 = null;

    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?
            privateKey2 = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain2 = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    assertNotNull(privateKey2);
    assertNotNull(privateKeyCertChain2);
}

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

/**
 * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#loadPKCS12Keystore(java.io.File, java.lang.String)}.
 * @throws CMException /*w ww  .j  a  v  a 2 s  . c o  m*/
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testLoadPKCS12Keystore()
        throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(
            new File(privateKeyFileURL.getPath()).toPath(), privateKeyAndPKCS12KeystorePassword);

    Key privateKey2 = null;
    Certificate[] privateKeyCertChain2 = null;

    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?
            privateKey2 = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain2 = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    assertNotNull(privateKey2);
    assertNotNull(privateKeyCertChain2);
}

From source file:org.eclipse.gyrex.admin.ui.http.jetty.internal.ImportCertificateDialog.java

void importKeystore(final InputStream in) throws Exception {
    KeyStore tempKs;
    if (keystoreTypeField.isSelected(0)) {
        tempKs = KeyStore.getInstance("JKS");
    } else if (keystoreTypeField.isSelected(1)) {
        tempKs = KeyStore.getInstance("PKCS12");
    } else {// ww  w . j  a v a 2 s .c  o  m
        throw new IllegalArgumentException(
                "Please select a keystore type before uploading a keystore and retry.");
    }

    final String keystorePassword = keyStorePasswordField.getText();
    final String keyPassword = keyPasswordField.getText();

    // load keystore
    tempKs.load(new BufferedInputStream(in), null != keystorePassword ? keystorePassword.toCharArray() : null);

    // initialize new JKS store
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);

    generatedKeystorePassword = UUID.randomUUID().toString().toCharArray();
    generatedKeyPassword = UUID.randomUUID().toString().toCharArray();

    // verify and copy into new store
    final Enumeration aliases = tempKs.aliases();
    while (aliases.hasMoreElements()) {
        final String alias = (String) aliases.nextElement();
        if (tempKs.isKeyEntry(alias)) {
            final Key key = tempKs.getKey(alias, null != keyPassword ? keyPassword.toCharArray()
                    : null != keystorePassword ? keystorePassword.toCharArray() : null);
            Certificate[] chain = tempKs.getCertificateChain(alias);
            if (null == chain) {
                final Certificate certificate = tempKs.getCertificate(alias);
                if (null == certificate) {
                    // skip to next
                    continue;
                }
                chain = new Certificate[] { certificate };
            }
            ks.setKeyEntry("jetty", key, generatedKeyPassword, chain);
            break;
        }
    }

    if (!ks.aliases().hasMoreElements()) {
        throw new IllegalArgumentException(
                "The uploaded keystore does not have a valid key + certificate chain entry. Please use a different keystore and retry.");
    }

    // write into bytes
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    ks.store(out, generatedKeystorePassword);

    keystoreBytes = out.toByteArray();
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

public CmsCAService(final HashMap<Object, Object> data) throws IllegalArgumentException {
    super(data);//from www  .j a va 2s.  c o m
    CryptoProviderTools.installBCProviderIfNotAvailable();
    loadData(data);
    if (this.data.get(KEYSTORE) != null) {
        // lookup keystore passwords      
        final String keystorepass = StringTools.passwordDecryption(EjbcaConfiguration.getCaCmsKeyStorePass(),
                "ca.cmskeystorepass");
        int status = ExtendedCAServiceInfo.STATUS_INACTIVE;
        try {
            if (log.isDebugEnabled()) {
                log.debug("Loading CMS keystore");
            }
            final KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(
                    new ByteArrayInputStream(Base64.decode(((String) this.data.get(KEYSTORE)).getBytes())),
                    keystorepass.toCharArray());
            if (log.isDebugEnabled()) {
                log.debug("Finished loading CMS keystore");
            }
            String alias = PRIVATESIGNKEYALIAS;
            privKey = (PrivateKey) keystore.getKey(alias, null);
            if (privKey == null) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "privKey was null for alias " + alias + ", trying with " + OLDPRIVATESIGNKEYALIAS);
                }
                alias = OLDPRIVATESIGNKEYALIAS;
                privKey = (PrivateKey) keystore.getKey(alias, null);
            }
            // Due to a bug in Glassfish v1 (fixed in v2), we used to have to make sure all certificates in this 
            // Array were of SUNs own provider, using CertTools.SYSTEM_SECURITY_PROVIDER.
            // As of EJBCA 3.9.3 we decided that we don't have to support Glassfish v1 anymore.
            Collection<Certificate> coll = CertTools
                    .getCertCollectionFromArray(keystore.getCertificateChain(alias), null);
            this.certificatechain = new ArrayList<Certificate>(coll);
            status = getStatus();
        } catch (Exception e) {
            log.error(
                    "Could not load keystore or certificate for CA CMS service. Perhaps the password was changed? "
                            + e.getMessage(),
                    e);
        } finally {
            info = new CmsCAServiceInfo(status, getSubjectDN(), getSubjectAltName(),
                    (String) this.data.get(KEYSPEC), (String) this.data.get(KEYALGORITHM),
                    this.certificatechain);
        }
        data.put(EXTENDEDCASERVICETYPE, Integer.valueOf(ExtendedCAServiceTypes.TYPE_CMSEXTENDEDSERVICE));
    } else {
        if (log.isDebugEnabled()) {
            log.debug("KEYSTORE is null when creating CmsCAService");
        }
    }
}

From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java

private int importKeyStoreTransacted(KeyStore keyStore, MissingKey missingKey) throws KeyStoreException {
    Check.notNull(keyStore, "keyStore");
    Check.notNull(missingKey, "missingKey");

    int importedEntries = 0;

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

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

        logger.debug("Alias: " + alias);

        Certificate certificate = keyStore.getCertificate(alias);

        if (!(certificate instanceof X509Certificate)) {
            /*// w  w  w .  jav  a 2s. com
             * only X509Certificates are supported
             */
            continue;
        }

        try {
            Key key = keyStore.getKey(alias, null);

            if (!(key instanceof PrivateKey)) {
                key = null;
            }

            if (key == null && missingKey == MissingKey.SKIP_CERTIFICATE) {
                logger.debug("Certificate found but missing Private key. Skipping certificate");

                continue;
            }

            KeyAndCertificate keyAndCertificate = new KeyAndCertificateImpl((PrivateKey) key,
                    (X509Certificate) certificate);

            if (keyAndCertStore.addKeyAndCertificate(keyAndCertificate)) {
                importedEntries++;
            }

            Certificate[] chain = keyStore.getCertificateChain(alias);

            importedEntries += importChain(chain);
        } catch (UnrecoverableKeyException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (NoSuchAlgorithmException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (KeyStoreException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (CertStoreException e) {
            logger.error("Unable to retrieve the key.", e);
        }
    }

    return importedEntries;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testBeIDSignature() throws Exception {
    Security.addProvider(new BeIDProvider());

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter();
    final BeIDCard beIDCard = getBeIDCard();
    keyStoreParameter.setBeIDCard(beIDCard);
    keyStoreParameter.setLogoff(true);//from   w w  w.  j ava2 s  .  co  m
    keyStore.load(keyStoreParameter);

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

    assertEquals(2, keyStore.size());

    assertTrue(keyStore.containsAlias("Signature"));
    assertTrue(keyStore.containsAlias("Authentication"));
    assertNotNull(keyStore.getCreationDate("Signature"));
    assertNotNull(keyStore.getCreationDate("Authentication"));

    assertTrue(keyStore.isKeyEntry("Signature"));
    final X509Certificate signCertificate = (X509Certificate) keyStore.getCertificate("Signature");
    assertNotNull(signCertificate);

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(authnCertificate);

    assertNotNull(keyStore.getCertificateChain("Signature"));
    assertNotNull(keyStore.getCertificateChain("Authentication"));

    assertTrue(keyStore.isKeyEntry("Authentication"));
    final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    assertNotNull(authnPrivateKey);

    assertTrue(keyStore.isKeyEntry("Signature"));
    final PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    assertNotNull(signPrivateKey);

    verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSA", signPrivateKey, signCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey());

    Security.addProvider(new BouncyCastleProvider());

    verifySignatureAlgorithm("SHA1withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey());
}

From source file:net.sf.keystore_explorer.gui.actions.GenerateCsrAction.java

/**
 * Do action./*from   ww  w.j ava  2  s.c  om*/
 */
@Override
protected void doAction() {
    File csrFile = null;
    FileOutputStream fos = null;

    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();
        Provider provider = history.getExplicitProvider();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());

        String keyPairAlg = privateKey.getAlgorithm();
        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        if (keyPairType == null) {
            throw new CryptoException(MessageFormat
                    .format(res.getString("GenerateCsrAction.NoCsrForKeyPairAlg.message"), keyPairAlg));
        }

        // determine dir of current keystore as proposal for CSR file location
        String path = CurrentDirectory.get().getAbsolutePath();
        File keyStoreFile = history.getFile();
        if (keyStoreFile != null) {
            path = keyStoreFile.getAbsoluteFile().getParent();
        }

        DGenerateCsr dGenerateCsr = new DGenerateCsr(frame, alias, privateKey, keyPairType, path, provider);
        dGenerateCsr.setLocationRelativeTo(frame);
        dGenerateCsr.setVisible(true);

        if (!dGenerateCsr.generateSelected()) {
            return;
        }

        CsrType format = dGenerateCsr.getFormat();
        SignatureType signatureType = dGenerateCsr.getSignatureType();
        String challenge = dGenerateCsr.getChallenge();
        String unstructuredName = dGenerateCsr.getUnstructuredName();
        boolean useCertificateExtensions = dGenerateCsr.isAddExtensionsWanted();
        csrFile = dGenerateCsr.getCsrFile();

        X509Certificate firstCertInChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)))[0];

        fos = new FileOutputStream(csrFile);

        if (format == CsrType.PKCS10) {
            String csr = Pkcs10Util.getCsrEncodedDerPem(Pkcs10Util.generateCsr(firstCertInChain, privateKey,
                    signatureType, challenge, unstructuredName, useCertificateExtensions, provider));

            fos.write(csr.getBytes());
        } else {
            SpkacSubject subject = new SpkacSubject(
                    X500NameUtils.x500PrincipalToX500Name(firstCertInChain.getSubjectX500Principal()));
            PublicKey publicKey = firstCertInChain.getPublicKey();

            // TODO handle other providers (PKCS11 etc)
            Spkac spkac = new Spkac(challenge, signatureType, subject, publicKey, privateKey);

            spkac.output(fos);
        }
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("GenerateCsrAction.NoWriteFile.message"), csrFile),
                res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("GenerateCsrAction.CsrGenerationSuccessful.message"),
            res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

public static TokenSearchResults searchTokenEntries(final KeyStore keyStore, final int startIndex,
        final int max, final QueryCriteria qc, final boolean includeData)
        throws CryptoTokenOfflineException, QueryException {
    final TokenSearchResults result;
    try {/*w w w.ja v  a 2  s.  com*/
        final ArrayList<TokenEntry> tokenEntries = new ArrayList<TokenEntry>();
        final Enumeration<String> e = keyStore.aliases(); // We assume the order is the same for every call unless entries has been added or removed

        final long maxIndex = (long) startIndex + max;
        for (int i = 0; i < maxIndex && e.hasMoreElements();) {
            final String keyAlias = e.nextElement();

            final String type;
            if (keyStore.entryInstanceOf(keyAlias, KeyStore.PrivateKeyEntry.class)) {
                type = TokenEntry.TYPE_PRIVATEKEY_ENTRY;
            } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) {
                type = TokenEntry.TYPE_SECRETKEY_ENTRY;
            } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.TrustedCertificateEntry.class)) {
                type = TokenEntry.TYPE_TRUSTED_ENTRY;
            } else {
                type = null;
            }

            TokenEntry entry = new TokenEntry(keyAlias, type);

            if (shouldBeIncluded(entry, qc)) {
                if (i < startIndex) {
                    i++;
                    continue;
                }

                if (LOG.isDebugEnabled()) {
                    LOG.debug("checking keyAlias: " + keyAlias);
                }

                // Add additional data
                if (includeData) {
                    Map<String, String> info = new HashMap<String, String>();
                    try {
                        Date creationDate = keyStore.getCreationDate(keyAlias);
                        entry.setCreationDate(creationDate);
                    } catch (ProviderException ex) {
                    } // NOPMD: We ignore if it is not supported

                    if (TokenEntry.TYPE_PRIVATEKEY_ENTRY.equals(type)) {
                        final Certificate[] chain = keyStore.getCertificateChain(keyAlias);
                        if (chain.length > 0) {
                            info.put(INFO_KEY_ALGORITHM,
                                    AlgorithmTools.getKeyAlgorithm(chain[0].getPublicKey()));
                            info.put(INFO_KEY_SPECIFICATION,
                                    AlgorithmTools.getKeySpecification(chain[0].getPublicKey()));
                        }
                        try {
                            entry.setParsedChain(chain);
                        } catch (CertificateEncodingException ex) {
                            info.put("Error", ex.getMessage());
                            LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
                        }
                    } else if (TokenEntry.TYPE_TRUSTED_ENTRY.equals(type)) {
                        Certificate certificate = keyStore.getCertificate(keyAlias);
                        try {
                            entry.setParsedTrustedCertificate(certificate);
                        } catch (CertificateEncodingException ex) {
                            info.put("Error", ex.getMessage());
                            LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
                        }
                    } else if (TokenEntry.TYPE_SECRETKEY_ENTRY.equals(type)) {
                        try {
                            KeyStore.Entry entry1 = keyStore.getEntry(keyAlias, null);
                            SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry1).getSecretKey();

                            info.put(INFO_KEY_ALGORITHM, secretKey.getAlgorithm());
                            //info.put(INFO_KEY_SPECIFICATION, AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); // TODO: Key specification support for secret keys
                        } catch (NoSuchAlgorithmException ex) {
                            info.put("Error", ex.getMessage());
                            LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
                        } catch (UnrecoverableEntryException ex) {
                            info.put("Error", ex.getMessage());
                            LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
                        }
                    }
                    entry.setInfo(info);
                }
                tokenEntries.add(entry);

                // Increase index
                i++;
            }
        }
        result = new TokenSearchResults(tokenEntries, e.hasMoreElements());
    } catch (KeyStoreException ex) {
        throw new CryptoTokenOfflineException(ex);
    }
    return result;
}

From source file:com.adito.boot.KeyStoreManager.java

/**
 * Import a key in PKCS12 key format/*from www  . jav a  2 s.  co m*/
 * 
 * @param keyFile file to import
 * @param password password for key
 * @param alias alias for key
 * @param newAlias 
 * @throws Exception on any error
 * @return the alias of the key imported
 */
public String importPKCS12Key(File keyFile, String password, String alias, String newAlias) throws Exception {
    KeyStore kspkcs12 = KeyStore.getInstance("PKCS12");
    kspkcs12.load(new FileInputStream(keyFile), password == null ? null : password.toCharArray());
    boolean hasTemp = false;
    if (isKeyStoreEmpty()) {
        if (isKeyStoreExists()) {
            deleteKeyStore();
        }
        createKeyStore();
        String dname = "cn=tmp, ou=tmp, o=tmp, l=tmp, st=tmp, c=GB";
        createKey("temporary-key", dname);
        hasTemp = true;
        reloadKeystore();
    }
    try {

        String firstAlias = (String) kspkcs12.aliases().nextElement();

        if (Util.isNullOrTrimmedBlank(alias)) {
            log.info("Alias not specified, importing first alias " + firstAlias);
            alias = firstAlias;
        }

        if (Util.isNullOrTrimmedBlank(newAlias)) {
            log.info("New alias not specified, using imported alias " + alias);
            newAlias = alias;
        }

        Certificate c[] = kspkcs12.getCertificateChain(alias);
        // Make sure we don't have a null chain
        if (c == null)
            c = new Certificate[] {};
        Key key = kspkcs12.getKey(alias, password == null ? null : password.toCharArray());
        if (key == null) {
            throw new Exception("No alias of '" + alias + "' in imported PKCS12 key file.");
        }
        this.keyStore.setKeyEntry(newAlias, key, getKeyStorePassword().toCharArray(), c);
    } finally {
        if (hasTemp || keyStore.containsAlias("temporary-key"))
            this.keyStore.deleteEntry("temporary-key");
        OutputStream out = null;
        try {
            out = new FileOutputStream(keyStoreFile.getAbsolutePath());
            getKeyStore().store(out, getKeyStorePassword().toCharArray());
        } finally {
            Util.closeStream(out);
        }
        updateRepository(false);
    }

    return newAlias;
}

From source file:com.sun.identity.console.user.model.UMChangeUserPasswordModelImpl.java

public void changePwd(String userId, String oldPassword, String newPassword) throws AMConsoleException {
    String[] params = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD };
    try {/*  w ww.j  a v a 2  s .com*/
        logEvent("ATTEMPT_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params);
        AMIdentity amIdentity = IdUtils.getIdentity(getUserSSOToken(), userId);
        boolean verified = verifyOldPassword(amIdentity, userId, oldPassword.toCharArray());
        if (!verified) {
            String strError = "Authorized for password changed denied";
            String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
            logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
            throw new AMConsoleException(strError);
        }
        Map passwordMap = new AMHashMap(2);
        Set set = new HashSet(2);
        set.add(newPassword);
        passwordMap.put(AMAdminConstants.ATTR_USER_PASSWORD, set);
        Set<String> attributeNames = new HashSet<String>();
        attributeNames.add(USERPKCS12_BINARY_ATTRNAME);
        Map<String, byte[][]> userPKCS12Map = amIdentity.getBinaryAttributes(attributeNames);
        if (userPKCS12Map != null && userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME) != null) {
            KeyStore keyStore = null;
            try {
                keyStore = KeyStore.getInstance(TOLVEN_CREDENTIAL_FORMAT_PKCS12);
            } catch (Exception e) {
                String strError = "Could not get an instance of KeyStore to create user KeyStore: "
                        + getErrorString(e);
                String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
                logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
                throw new AMConsoleException(strError);
            }
            byte[][] oldUserPKCS12ByteArrs = (byte[][]) userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME);
            byte[] oldUserPKCS12 = oldUserPKCS12ByteArrs[0];
            ByteArrayInputStream bais = new ByteArrayInputStream(oldUserPKCS12);
            try {
                keyStore.load(bais, oldPassword.toCharArray());
            } catch (Exception e) {
                String strError = "Could not get user KeyStore using old password: " + getErrorString(e);
                String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
                logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
                throw new AMConsoleException(strError);
            }
            ByteArrayOutputStream baos = null;
            try {
                String alias = keyStore.aliases().nextElement();
                PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, oldPassword.toCharArray());
                keyStore.setKeyEntry(alias, privateKey, newPassword.toCharArray(),
                        keyStore.getCertificateChain(alias));
                baos = new ByteArrayOutputStream();
            } catch (Exception e) {
                String strError = "Could not get Key from user KeyStore: " + getErrorString(e);
                String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
                logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
                throw new AMConsoleException(strError);
            }
            try {
                keyStore.store(baos, newPassword.toCharArray());
            } catch (Exception e) {
                String strError = "Could not save user KeyStore: " + getErrorString(e);
                String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
                logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
                throw new AMConsoleException(strError);
            }
            byte[] newUserPKCS12 = baos.toByteArray();
            byte[][] newUserPKCS12ByteArrs = new byte[1][];
            newUserPKCS12ByteArrs[0] = newUserPKCS12;
            Map<String, byte[][]> newUserPKCS12Map = newUserPKCS12Map = new HashMap<String, byte[][]>();
            newUserPKCS12Map.put(USERPKCS12_BINARY_ATTRNAME, newUserPKCS12ByteArrs);
            // Ensure that the following two lines are never out of sync (one would expect store() to be a transaction)
            amIdentity.setBinaryAttributes(newUserPKCS12Map);
            amIdentity.setAttributes(passwordMap);
            amIdentity.store();
        } else {
            amIdentity.setAttributes(passwordMap);
            amIdentity.store();
        }
        logEvent("SUCCEED_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params);
    } catch (SSOException e) {
        String strError = getErrorString(e);
        String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
        logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
        throw new AMConsoleException(strError);
    } catch (IdRepoException e) {
        String strError = getErrorString(e);
        String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
        logEvent("IDM_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
        throw new AMConsoleException(strError);
    }
}