} 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));