Example usage for java.security PrivateKey getAlgorithm

List of usage examples for java.security PrivateKey getAlgorithm

Introduction

In this page you can find the example usage for java.security PrivateKey getAlgorithm.

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:org.cesecore.certificates.ca.X509CA.java

@Override
public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain)
        throws SignRequestSignatureException {
    // First verify that we signed this certificate
    try {/*  w w w  . j  a va2  s  .co  m*/
        if (cert != null) {
            final PublicKey verifyKey;
            final X509Certificate cacert = (X509Certificate) getCACertificate();
            if (cacert != null) {
                verifyKey = cacert.getPublicKey();
            } else {

                verifyKey = cryptoToken
                        .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));

            }
            cert.verify(verifyKey);
        }
    } catch (CryptoTokenOfflineException e) {
        throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7",
                e);
    } catch (InvalidKeyException e) {
        throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e);
    } catch (CertificateException e) {
        throw new SignRequestSignatureException("An encoding error was encountered.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignRequestSignatureException(
                "The certificate provided was signed with an invalid algorithm.", e);
    } catch (NoSuchProviderException e) {
        throw new SignRequestSignatureException(
                "The crypto provider was not found for verification of the certificate.", e);
    } catch (SignatureException e) {
        throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?",
                e);
    }

    Collection<Certificate> chain = getCertificateChain();
    ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>();
    try {
        if (cert != null) {
            certList.add(new JcaX509CertificateHolder((X509Certificate) cert));
        }
        if (includeChain) {
            for (Certificate certificate : chain) {
                certList.add(new JcaX509CertificateHolder((X509Certificate) certificate));
            }
        }
    } catch (CertificateEncodingException e) {
        throw new SignRequestSignatureException("Could not encode certificate", e);
    }
    try {
        CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes());
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        final PrivateKey privateKey = cryptoToken
                .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        if (privateKey == null) {
            String msg1 = "createPKCS7: Private key does not exist!";
            log.debug(msg1);
            throw new SignRequestSignatureException(msg1);
        }
        String signatureAlgorithmName = AlgorithmTools
                .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm());
        try {
            ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(cryptoToken.getSignProviderName()).build(privateKey);
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate()));
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e);
        }
        gen.addCertificates(new CollectionStore(certList));
        CMSSignedData s = null;
        CAToken catoken = getCAToken();
        if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) {
            log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm "
                    + privateKey.getAlgorithm());
            s = gen.generate(msg, true);
        } else {
            String msg1 = "CA Token does not exist!";
            log.debug(msg);
            throw new SignRequestSignatureException(msg1);
        }
        return s.getEncoded();
    } catch (CryptoTokenOfflineException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        //FIXME: This right here is just nasty
        throw new RuntimeException(e);
    }
}

From source file:org.wildfly.security.x500.cert.acme.AcmeClientSpiTest.java

private void obtainCertificateChain(String keyAlgorithmName, int keySize, AcmeAccount account,
        String domainName) throws Exception {
    X509CertificateChainAndSigningKey certificateChainAndSigningKey = acmeClient.obtainCertificateChain(account,
            false, keyAlgorithmName, keySize, domainName);
    PrivateKey privateKey = certificateChainAndSigningKey.getSigningKey();

    X509Certificate[] replyCertificates = certificateChainAndSigningKey.getCertificateChain();
    assertTrue(replyCertificates.length == 2);
    X509Certificate signedCert = replyCertificates[0];
    X509Certificate caCert = replyCertificates[1];
    assertTrue(signedCert.getSubjectDN().getName().contains(domainName));
    assertEquals(caCert.getSubjectDN(), signedCert.getIssuerDN());
    assertEquals("CN=cackling cryptographer fake ROOT", caCert.getIssuerDN().getName());
    if (keyAlgorithmName != null && keySize != -1) {
        assertEquals(keyAlgorithmName, privateKey.getAlgorithm());
        assertEquals(keyAlgorithmName, signedCert.getPublicKey().getAlgorithm());
        if (keyAlgorithmName.equals("EC")) {
            assertEquals(keySize,/*from  ww w .ja  va2 s.  c o  m*/
                    ((ECPublicKey) signedCert.getPublicKey()).getParams().getCurve().getField().getFieldSize());
        } else if (keyAlgorithmName.equals("RSA")) {
            assertEquals(keySize, ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength());
        }
    } else {
        if (signedCert.getPublicKey().getAlgorithm().equals("RSA")) {
            assertEquals(AcmeClientSpi.DEFAULT_KEY_SIZE,
                    ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength());
            assertEquals("RSA", privateKey.getAlgorithm());
        } else if (signedCert.getPublicKey().getAlgorithm().equals("EC")) {
            assertEquals(AcmeClientSpi.DEFAULT_EC_KEY_SIZE,
                    ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength());
            assertEquals("EC", privateKey.getAlgorithm());
        }
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void importCAFromKeyStore(AuthenticationToken admin, String caname, byte[] p12file, String keystorepass,
        String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) {
    try {/*from   w  w w  .j a v a 2s.c  om*/
        // check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocreateca", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), null, null, null, details);
        }
        // load keystore
        java.security.KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(new java.io.ByteArrayInputStream(p12file), keystorepass.toCharArray());
        // Extract signature keys
        if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) {
            throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found.");
        }
        Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias);
        if (signatureCertChain.length < 1) {
            String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias;
            log.error(msg);
            throw new Exception(msg);
        }
        Certificate caSignatureCertificate = (Certificate) signatureCertChain[0];
        PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey();
        PrivateKey p12PrivateSignatureKey = null;
        p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias,
                privkeypass.toCharArray());
        log.debug("ImportSignatureKeyAlgorithm=" + p12PrivateSignatureKey.getAlgorithm());

        // Extract encryption keys
        PrivateKey p12PrivateEncryptionKey = null;
        PublicKey p12PublicEncryptionKey = null;
        Certificate caEncryptionCertificate = null;
        if (privateEncryptionKeyAlias != null) {
            if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found.");
            }
            Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias);
            if (encryptionCertChain.length < 1) {
                String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias;
                log.error(msg);
                throw new Exception(msg);
            }
            caEncryptionCertificate = (Certificate) encryptionCertChain[0];
            p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias,
                    privkeypass.toCharArray());
            p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey();
        }
        importCAFromKeys(admin, caname, keystorepass, signatureCertChain, p12PublicSignatureKey,
                p12PrivateSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey);
    } catch (Exception e) {
        String detailsMsg = intres.getLocalizedMessage("caadmin.errorimportca", caname, "PKCS12",
                e.getMessage());
        auditSession.log(EjbcaEventTypes.CA_IMPORT, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, detailsMsg);
        throw new EJBException(e);
    }
}

From source file:org.ejbca.util.keystore.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is
 * set to 'privateKey' and the private key password is null.
 *
 * @param alias the alias used for the key entry
 * @param privKey RSA private key/*  w  w  w .  java  2  s.  co  m*/
 * @param cert user certificate
 * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i;
                }
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i);
                }
                if (cafriendly == null) {
                    cafriendly = "CA_unknown" + i;
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public byte[] exportCAKeyStore(AuthenticationToken admin, String caname, String keystorepass,
        String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) {
    log.trace(">exportCAKeyStore");
    try {/* ww w  .ja  v  a2 s. c om*/
        final CA thisCa = caSession.getCAForEdit(admin, caname);
        // Make sure we are not trying to export a hard or invalid token
        CAToken thisCAToken = thisCa.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId());
        if (!(cryptoToken instanceof SoftCryptoToken)) {
            throw new IllegalCryptoTokenException("Cannot export anything but a soft token.");
        }
        // Do not allow export without password protection
        if (StringUtils.isEmpty(keystorepass) || StringUtils.isEmpty(privkeypass)) {
            throw new IllegalArgumentException("Cannot export a token without password protection.");
        }
        // Check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoexportcatoken", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
            throw new AuthorizationDeniedException(msg);
        }
        // Fetch keys
        final char[] password = keystorepass.toCharArray();
        ((SoftCryptoToken) cryptoToken).checkPasswordBeforeExport(password);
        cryptoToken.activate(password);

        PrivateKey p12PrivateEncryptionKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PublicKey p12PublicEncryptionKey = cryptoToken
                .getPublicKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PrivateKey p12PrivateCertSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        PrivateKey p12PrivateCRLSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN));
        if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) {
            throw new Exception("Assertion of equal signature keys failed.");
        }
        // Proceed with the export
        byte[] ret = null;
        String format = null;
        if (thisCa.getCAType() == CAInfo.CATYPE_CVC) {
            log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm()
                    + " of format: " + p12PrivateCertSignKey.getFormat());
            format = p12PrivateCertSignKey.getFormat();
            ret = p12PrivateCertSignKey.getEncoded();
        } else {
            log.debug("Exporting PKCS12 keystore");
            format = "PKCS12";
            KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(null, keystorepass.toCharArray());
            // Load keys into keystore
            Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain()
                    .toArray(new Certificate[0]);
            Certificate[] certificateChainEncryption = new Certificate[1];
            // certificateChainSignature[0].getSigAlgName(),
            // generate dummy certificate for encryption key.
            certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null,
                    p12PrivateEncryptionKey, p12PublicEncryptionKey, thisCAToken.getEncryptionAlgorithm(), true,
                    X509KeyUsage.keyEncipherment, true);
            log.debug("Exporting with sigAlgorithm "
                    + AlgorithmTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm="
                    + thisCAToken.getEncryptionAlgorithm());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore.");
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore.");
            }

            keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass.toCharArray(),
                    certificateChainSignature);
            keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass.toCharArray(),
                    certificateChainEncryption);
            // Return KeyStore as byte array and clean up
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            keystore.store(baos, keystorepass.toCharArray());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                keystore.deleteEntry(privateSignatureKeyAlias);
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                keystore.deleteEntry(privateEncryptionKeyAlias);
            }
            ret = baos.toByteArray();
        }
        String msg = intres.getLocalizedMessage("caadmin.exportedca", caname, format);
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
        log.trace("<exportCAKeyStore");
        return ret;
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("caadmin.errorexportca", caname, "PKCS12", e.getMessage());
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, details);
        throw new EJBException(e);
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is set to 'privateKey' and the private key password is
 * null.//ww w  . j a v  a  2s . c  om
 * 
 * @param alias
 *            the alias used for the key entry
 * @param privKey
 *            RSA private key
 * @param cert
 *            user certificate
 * @param cachain
 *            CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception
 *                if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O");
                    if (cafriendly == null) {
                        cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU");
                        if (cafriendly == null) {
                            cafriendly = "CA_unknown" + i;
                        } else {
                            cafriendly = cafriendly + i;
                        }
                    } else {
                        cafriendly = cafriendly + i;
                    }
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}