Example usage for org.bouncycastle.pkcs PKCS12SafeBag friendlyNameAttribute

List of usage examples for org.bouncycastle.pkcs PKCS12SafeBag friendlyNameAttribute

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs PKCS12SafeBag friendlyNameAttribute.

Prototype

ASN1ObjectIdentifier friendlyNameAttribute

To view the source code for org.bouncycastle.pkcs PKCS12SafeBag friendlyNameAttribute.

Click Source Link

Usage

From source file:com.aqnote.shared.cryptology.cert.io.PKCSWriter.java

License:Open Source License

public static void storePKCS12File(X509Certificate[] chain, PrivateKey key, char[] pwd, OutputStream ostream)
        throws Exception {
    if (chain == null || key == null || ostream == null)
        return;//from   ww w.j a  v  a2 s. co m

    PKCS12SafeBag[] certSafeBags = new PKCS12SafeBag[chain.length];
    for (int i = chain.length - 1; i > 0; i--) {
        PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(chain[i]);
        safeBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
                new DERBMPString(CertificateUtil.getSubjectCN(chain[i])));
        certSafeBags[i] = safeBagBuilder.build();
    }

    X509Certificate cert = chain[0];
    String subjectCN = CertificateUtil.getSubjectCN(cert);
    SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(cert.getPublicKey());

    PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(cert);
    safeBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(subjectCN));
    safeBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);
    certSafeBags[0] = safeBagBuilder.build();

    PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder();
    // desEDE/id_aes256_CBC
    OutputEncryptor oKeyEncryptor = new JcePKCSPBEOutputEncryptorBuilder(pbeWithSHAAnd3_KeyTripleDES_CBC)
            .setProvider(JCE_PROVIDER).build(pwd);
    PKCS12SafeBagBuilder keySafeBagBuilder = new JcaPKCS12SafeBagBuilder(key, oKeyEncryptor);
    keySafeBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(subjectCN));
    keySafeBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);
    pfxPduBuilder.addData(keySafeBagBuilder.build());

    OutputEncryptor oCertEncryptor = new JcePKCSPBEOutputEncryptorBuilder(pbeWithSHAAnd40BitRC2_CBC)
            .setProvider(JCE_PROVIDER).build(pwd);
    pfxPduBuilder.addEncryptedData(oCertEncryptor, certSafeBags);

    // PKCS12PfxPdu pfxPdu = pfxPduBuilder.build(new JcePKCS12MacCalculatorBuilder(idSHA1), pwd);
    BcPKCS12MacCalculatorBuilder builder = new BcPKCS12MacCalculatorBuilder(new SHA1Digest(),
            new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE));
    PKCS12PfxPdu pfxPdu = pfxPduBuilder.build(builder, pwd);

    ostream.write(pfxPdu.getEncoded(ASN1Encoding.DER));
    ostream.close();
}

From source file:com.aqnote.shared.cryptology.cert.util.KeyStoreUtil.java

License:Open Source License

public static KeyStore readPKCS12KeyStore(String alias, Certificate[] chain, KeyPair keyPair, char[] pwd)
        throws Exception {
    PKCS12SafeBagBuilder BagBuilder = new JcaPKCS12SafeBagBuilder((X509Certificate) chain[0]);
    BagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(alias));
    SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic());
    BagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

    KeyStore store = KeyStore.getInstance(KEY_STORE_TYPE, JCE_PROVIDER);
    store.load(null, null);/*from   w  w w . j a  va2s  . com*/
    store.setKeyEntry(alias, keyPair.getPrivate(), pwd, chain);

    return store;
}

From source file:com.aqnote.shared.encrypt.cert.bc.cover.PKCSWriter.java

License:Open Source License

public static void storePKCS12File(X509Certificate[] chain, PrivateKey key, char[] pwd, OutputStream ostream)
        throws Exception {
    if (chain == null || key == null || ostream == null)
        return;/*from  w  w  w  . jav  a 2  s .  com*/

    PKCS12SafeBag[] certSafeBags = new PKCS12SafeBag[chain.length];
    for (int i = chain.length - 1; i > 0; i--) {
        PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(chain[i]);
        safeBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
                new DERBMPString(CertificateUtil.getSubjectCN(chain[i])));
        certSafeBags[i] = safeBagBuilder.build();
    }

    X509Certificate cert = (X509Certificate) chain[0];
    String subjectCN = CertificateUtil.getSubjectCN(cert);
    SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(cert.getPublicKey());

    PKCS12SafeBagBuilder safeBagBuilder = new JcaPKCS12SafeBagBuilder(cert);
    safeBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(subjectCN));
    safeBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);
    certSafeBags[0] = safeBagBuilder.build();

    PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder();
    // desEDE/id_aes256_CBC
    OutputEncryptor oKeyEncryptor = new JcePKCSPBEOutputEncryptorBuilder(pbeWithSHAAnd3_KeyTripleDES_CBC)
            .setProvider(JCE_PROVIDER).build(pwd);
    PKCS12SafeBagBuilder keySafeBagBuilder = new JcaPKCS12SafeBagBuilder(key, oKeyEncryptor);
    keySafeBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(subjectCN));
    keySafeBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);
    pfxPduBuilder.addData(keySafeBagBuilder.build());

    OutputEncryptor oCertEncryptor = new JcePKCSPBEOutputEncryptorBuilder(pbeWithSHAAnd40BitRC2_CBC)
            .setProvider(JCE_PROVIDER).build(pwd);
    pfxPduBuilder.addEncryptedData(oCertEncryptor, certSafeBags);

    // PKCS12PfxPdu pfxPdu = pfxPduBuilder.build(new
    // JcePKCS12MacCalculatorBuilder(idSHA1), pwd);
    PKCS12PfxPdu pfxPdu = pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), pwd);

    ostream.write(pfxPdu.getEncoded(ASN1Encoding.DER));
    ostream.close();
}

From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java

License:Apache License

/**
 * Return the key store object as a PKCS#12 byte array.
 *
 * @param password the password to use to encrypt the key data.
 * @return an array of bytes representing the encoding.
 * @throws IOException on a conversion to ASN.1 encoding error.
 * @throws GeneralSecurityException if there is an issue encrypting the key data.
 *//*from   ww w .  j a  v  a2  s.  c o m*/
public synchronized byte[] getEncoded(char[] password) throws IOException, GeneralSecurityException {
    KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");

    EllipticCurve curve = new EllipticCurve(
            new ECFieldFp(
                    new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

    ECParameterSpec spec = new ECParameterSpec(curve,
            ECPointUtil.decodePoint(curve,
                    Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n
            1); // h

    // TODO: neeed an EC key for the node
    ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec(
            new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
            spec);

    try {
        OutputEncryptor encOut = new JcePKCSPBEOutputEncryptorBuilder(NISTObjectIdentifiers.id_aes256_CBC)
                .setProvider("BC").build(password);

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder();

        for (String keyID : sharedPrivateKeyMap.keySet()) {
            PrivateKey sigKey = fact.generatePrivate(priKeySpec);
            SubjectPublicKeyInfo pubKey = this.fetchPublicKey(keyID);

            PKCS12SafeBagBuilder eeCertBagBuilder = new PKCS12SafeBagBuilder(
                    createCertificate(keyID, sequenceNoMap.get(keyID), sigKey));

            eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(keyID));

            SubjectKeyIdentifier pubKeyId = extUtils.createSubjectKeyIdentifier(pubKey);

            eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

            PKCS12SafeBagBuilder keyBagBuilder = new PKCS12SafeBagBuilder(PrivateKeyInfoFactory
                    .createPrivateKeyInfo(sharedPrivateKeyMap.get(keyID), paramsMap.get(keyID)), encOut);

            keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(keyID));
            keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

            builder.addEncryptedData(
                    new JcePKCSPBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC)
                            .setProvider("BC").build(password),
                    new PKCS12SafeBag[] { eeCertBagBuilder.build() });

            builder.addData(keyBagBuilder.build());
        }

        PKCS12PfxPdu pfx = builder.build(new JcePKCS12MacCalculatorBuilder(NISTObjectIdentifiers.id_sha256),
                password);

        return pfx.getEncoded(ASN1Encoding.DL);
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to create key store: " + e.getMessage(), e);
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException("Unable to create operator: " + e.getMessage(), e);
    }
}

From source file:com.vvote.thirdparty.ximix.util.BLSKeyStore.java

License:Apache License

private String getKeyID(Attribute[] attributes) {
    for (Attribute attr : attributes) {
        if (PKCS12SafeBag.friendlyNameAttribute.equals(attr.getAttrType())) {
            return DERBMPString.getInstance(attr.getAttrValues().getObjectAt(0)).getString();
        }/*from   w w  w  .  j  av  a  2 s  .co  m*/
    }

    throw new IllegalStateException("No friendlyNameAttribute found.");
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java

License:Apache License

/**
 * A method to create PKCS12 file that stores the certificates.
 * @param pfxOut: the output of pkcs12 file (in OutputStream) 
 * @param key: private key that is associated with the credential
 * @param chain: chain of certificates (within the credential)
 * @param keyPasswd: key password/* w  w  w  . j a va 2 s  . co m*/
 * @throws Exception
 */
public static void createPKCS12FileBc(OutputStream pfxOut, AsymmetricKeyParameter key,
        X509CertificateHolder[] chain, char[] keyPasswd) throws Exception {

    OutputEncryptor encOut = new BcPKCS12PBEOutputEncryptorBuilder(
            PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine()))
                    .build(keyPasswd);

    PKCS12SafeBagBuilder taCertBagBuilder = null;
    PKCS12SafeBagBuilder caCertBagBuilder = null;
    PKCS12SafeBagBuilder eeCertBagBuilder = null;
    SubjectKeyIdentifier pubKeyId = null;

    // identify the type of certificate from the given certificate chain
    for (int i = 0; i < chain.length; i++) {
        Extensions exs = chain[i].getExtensions();
        if (exs != null) {
            KeyUsage ku = KeyUsage.fromExtensions(exs);
            if (ku.toString().equals("KeyUsage: 0x" + Integer.toHexString(128 | 32))) {
                // end entity certificate
                eeCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]);
                BcX509ExtensionUtils extUtils = new BcX509ExtensionUtils();
                eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
                        new DERBMPString("Eric's Key"));
                pubKeyId = extUtils.createSubjectKeyIdentifier(chain[i].getSubjectPublicKeyInfo());
                eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);
            } else if (ku.toString().equals("KeyUsage: 0x" + Integer.toHexString(128 | 4 | 2))) {
                // intermediate certificate
                caCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]);
                caCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
                        new DERBMPString("BETaaS Intermediate Certificate"));
            }
        } else {
            // root certificate
            taCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]);
            taCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute,
                    new DERBMPString("BETaaS Primary Certificate"));
        }
    }

    //    PKCS12SafeBagBuilder taCertBagBuilder = new PKCS12SafeBagBuilder(chain[2]);

    //    PKCS12SafeBagBuilder caCertBagBuilder = new PKCS12SafeBagBuilder(chain[1]);

    //    PKCS12SafeBagBuilder eeCertBagBuilder = new PKCS12SafeBagBuilder(chain[0]);

    // the ECPrivateKey, consists of the key itself and the ECParams
    BigInteger dPriv = ((ECPrivateKeyParameters) key).getD();
    X9ECParameters ecParams = new X9ECParameters(((ECKeyParameters) key).getParameters().getCurve(),
            ((ECKeyParameters) key).getParameters().getG(), ((ECKeyParameters) key).getParameters().getN(),
            ((ECKeyParameters) key).getParameters().getH(), ((ECKeyParameters) key).getParameters().getSeed());
    ECPrivateKey privParams = new ECPrivateKey(dPriv, ecParams);

    // include the ecParams
    AlgorithmIdentifier sigAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ecParams);

    //    PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(key);

    PKCS12SafeBagBuilder keyBagBuilder = new PKCS12SafeBagBuilder(new PrivateKeyInfo(sigAlg, privParams),
            encOut);

    keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key"));
    if (pubKeyId != null)
        keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

    PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder();

    builder.addData(keyBagBuilder.build());

    // no need to insert SHA1Digest() because it is the default Digest algorithm
    // check each of the certbagbuilder
    if (caCertBagBuilder != null && taCertBagBuilder != null && eeCertBagBuilder != null) {
        // include all types of certificate in the file --> root own's credential
        builder.addEncryptedData(
                new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC,
                        new CBCBlockCipher(new RC2Engine())).build(keyPasswd),
                new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build(),
                        taCertBagBuilder.build() });
    } else if (caCertBagBuilder != null && taCertBagBuilder != null && eeCertBagBuilder == null) {
        // only root and intermediate --> signer credential
        builder.addEncryptedData(
                new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC,
                        new CBCBlockCipher(new RC2Engine())).build(keyPasswd),
                new PKCS12SafeBag[] { caCertBagBuilder.build(), taCertBagBuilder.build() });
    } else if (caCertBagBuilder == null && taCertBagBuilder == null) {
        // only end entity --> e.g. application, user, etc
        builder.addEncryptedData(
                new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC,
                        new CBCBlockCipher(new RC2Engine())).build(keyPasswd),
                new PKCS12SafeBag[] { eeCertBagBuilder.build() });
    } else if (caCertBagBuilder != null && taCertBagBuilder == null && eeCertBagBuilder != null) {
        // only intermediate and end entity --> common GW certificate
        builder.addEncryptedData(
                new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC,
                        new CBCBlockCipher(new RC2Engine())).build(keyPasswd),
                new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build() });
    }

    //    PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder(
    //          new SHA256Digest(), 
    //          new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)), keyPasswd);
    PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder(), keyPasswd);
    // make sure we don't include indefinite length encoding
    pfxOut.write(pfx.getEncoded(ASN1Encoding.DL));

    pfxOut.close();
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java

License:Apache License

/**
 * A method to load BcCredential (consists of certificate chain, end entity 
 * alias and private key of end entity credential) from the PKCS12 file
 * @param pkcs12FileName: the PKCS12 file name
 * @param keyPasswd: the password of the key credential
 * @return/*from   w w  w .  j a  v  a  2s  .  c  o m*/
 * @throws Exception
 */
public static BcCredential loadPKCS12Credential(String pkcs12FileName, char[] keyPasswd, int certType) {

    PKCS12PfxPdu pfxPdu = null;
    //     if(certType == APPS_CERT){
    //        log.info("Reading AppStoreCertInter.p12 file");
    //        InputStream is = PKCS12Utils.class.getResourceAsStream(pkcs12FileName);
    //        log.info("AppStoreCertInter.p12 file has been converted to InputStream");
    //        pfxPdu = new PKCS12PfxPdu(Streams.readAll(is));
    //        log.info("Read the PKCS12PfxPdu...");
    //     }
    //     else if(certType == GW_CERT){
    // Try to put the AppStoreCertInter.p12 in the karaf, so no need to read
    // from the resource, e.g. getResourceAsStream
    log.debug("will start loading PKCS12 file...");
    try {
        pfxPdu = new PKCS12PfxPdu(Streams.readAll(new FileInputStream(pkcs12FileName)));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        log.error("PKCS12 file: " + pkcs12FileName + " is not found!!");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error("IOException in initializing PKCS12PfxPdu...");
        e.printStackTrace();
    }
    log.debug("Loading PKCS12 successfully...");
    //     }
    try {
        if (!pfxPdu.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE),
                keyPasswd)) {
            log.error("PKCS#12 MAC test failed!");
            return null;
        }
    } catch (PKCSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ContentInfo[] infos = pfxPdu.getContentInfos();
    InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder()
            .build(keyPasswd);

    String eeAlias = null;
    AsymmetricKeyParameter privCred = null;
    List<X509CertificateHolder> chainList = new ArrayList<X509CertificateHolder>();
    //    log.info("Start iterating over the ContentInfo...");
    for (int i = 0; i != infos.length; i++) {
        if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = null;
            try {
                dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);
            } catch (PKCSException e) {
                // TODO Auto-generated catch block
                log.error("Error in initiating PKCS12SafeBagFactory...");
                e.printStackTrace();
            }

            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            for (int b = 0; b != bags.length; b++) {
                PKCS12SafeBag bag = bags[b];
                X509CertificateHolder certHldr = (X509CertificateHolder) bag.getBagValue();
                chainList.add(certHldr);
                log.debug("Found a certificate and add it to certificate chain...");
            }
        } else {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();

            PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
            PrivateKeyInfo info;
            AsymmetricKeyParameter privKey = null;
            try {
                info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
                privKey = PrivateKeyFactory.createKey(info);
            } catch (PKCSException e) {
                // TODO Auto-generated catch block
                log.error("Error in getting the decrypt private key info...");
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.error("Error in loading private key...");
                e.printStackTrace();
            }

            Attribute[] attributes = bags[0].getAttributes();
            for (int a = 0; a != attributes.length; a++) {
                Attribute attr = attributes[a];
                if (attr.getAttrType().equals(PKCS12SafeBag.friendlyNameAttribute)) {
                    eeAlias = ((DERBMPString) attr.getAttributeValues()[0]).getString();
                    privCred = privKey;
                    log.debug("Get end entity alias");
                    log.debug("Priv. credential D: " + ((ECPrivateKeyParameters) privCred).getD().toString());
                }
            }
        }
    }
    X509CertificateHolder[] chain = new X509CertificateHolder[chainList.size()];
    chain = (X509CertificateHolder[]) chainList.toArray(chain);

    BcCredential cred = new BcCredential(eeAlias, privCred, chain);
    log.debug("Credential has been loaded!!");

    return cred;
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java

License:Apache License

/**
 * A method to load BcCredential (consists of certificate chain, end entity 
 * alias and private key of end entity credential) from the PKCS12 file
 * @param pfx: the PKCS#12 file in byte//from  w w  w . j a va 2  s  .  c o  m
 * @param keyPasswd: the password of the key credential
 * @return
 * @throws Exception
 */
public static BcCredential loadPKCS12Credential(byte[] pfx, char[] keyPasswd) throws Exception {

    PKCS12PfxPdu pfxPdu = new PKCS12PfxPdu(pfx);

    if (!pfxPdu.isMacValid(new BcPKCS12MacCalculatorBuilderProvider(BcDefaultDigestProvider.INSTANCE),
            keyPasswd)) {
        log.error("PKCS#12 MAC test failed!");
        return null;
    }

    ContentInfo[] infos = pfxPdu.getContentInfos();
    InputDecryptorProvider inputDecryptorProvider = new BcPKCS12PBEInputDecryptorProviderBuilder()
            .build(keyPasswd);

    String eeAlias = null;
    AsymmetricKeyParameter privCred = null;
    List<X509CertificateHolder> chainList = new ArrayList<X509CertificateHolder>();
    //    log.debug("Start iterating over the ContentInfo...");
    for (int i = 0; i != infos.length; i++) {
        if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);

            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            for (int b = 0; b != bags.length; b++) {
                PKCS12SafeBag bag = bags[b];
                X509CertificateHolder certHldr = (X509CertificateHolder) bag.getBagValue();
                chainList.add(certHldr);
                log.debug("Found a certificate and add it to certificate chain...");
            }
        } else {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();

            PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
            PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
            AsymmetricKeyParameter privKey = PrivateKeyFactory.createKey(info);

            Attribute[] attributes = bags[0].getAttributes();
            for (int a = 0; a != attributes.length; a++) {
                Attribute attr = attributes[a];
                if (attr.getAttrType().equals(PKCS12SafeBag.friendlyNameAttribute)) {
                    eeAlias = ((DERBMPString) attr.getAttributeValues()[0]).getString();
                    privCred = privKey;
                    log.debug("Get end entity alias");
                    log.debug("Priv. credential D: " + ((ECPrivateKeyParameters) privCred).getD().toString());
                }
            }
        }
    }
    X509CertificateHolder[] chain = new X509CertificateHolder[chainList.size()];
    chain = (X509CertificateHolder[]) chainList.toArray(chain);

    BcCredential cred = new BcCredential(eeAlias, privCred, chain);

    return cred;
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.BLSKeyManager.java

License:Apache License

public synchronized byte[] getEncoded(char[] password) throws IOException, GeneralSecurityException {
    try {//from w w w .  ja  v a  2  s .c  o  m
        OutputEncryptor encOut = new JcePKCSPBEOutputEncryptorBuilder(NISTObjectIdentifiers.id_aes256_CBC)
                .setProvider("BC").build(password);

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder();

        for (String keyID : sharedPrivateKeyMap.getIDs()) {
            SubjectPublicKeyInfo pubKey = this.fetchPublicKey(keyID);

            // TODO: perhaps add CA cert and trust anchor to key store if available
            PKCS12SafeBagBuilder eeCertBagBuilder = new PKCS12SafeBagBuilder(
                    createCertificate(keyID, sharedPrivateKeyMap.getShare(keyID).getSequenceNo(),
                            (PrivateKey) nodeContext.getNodeCAStore().getKey("nodeCA", new char[0])));

            eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(keyID));

            SubjectKeyIdentifier pubKeyId = extUtils.createSubjectKeyIdentifier(pubKey);

            eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

            PKCS12SafeBagBuilder keyBagBuilder = new PKCS12SafeBagBuilder(PrivateKeyInfoFactory
                    .createPrivateKeyInfo(sharedPrivateKeyMap.getShare(keyID).getValue(), paramsMap.get(keyID)),
                    encOut);

            keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(keyID));
            keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

            builder.addEncryptedData(
                    new JcePKCSPBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC)
                            .setProvider("BC").build(password),
                    new PKCS12SafeBag[] { eeCertBagBuilder.build() });

            builder.addData(keyBagBuilder.build());
        }

        PKCS12PfxPdu pfx = builder.build(new JcePKCS12MacCalculatorBuilder(NISTObjectIdentifiers.id_sha256),
                password);

        return pfx.getEncoded(ASN1Encoding.DL);
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to create key store: " + e.getMessage(), e);
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException("Unable to create operator: " + e.getMessage(), e);
    }
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.ECKeyManager.java

License:Apache License

public synchronized byte[] getEncoded(char[] password) throws IOException, GeneralSecurityException {
    KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");

    try {/*from  w  ww .j  a  v  a 2  s.com*/
        OutputEncryptor encOut = new JcePKCSPBEOutputEncryptorBuilder(NISTObjectIdentifiers.id_aes256_CBC)
                .setProvider("BC").build(password);

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder();

        for (String keyID : sharedPrivateKeyMap.getIDs()) {
            ECDomainParameters domainParams = paramsMap.get(keyID);
            PrivateKey privKey = fact
                    .generatePrivate(new PKCS8EncodedKeySpec(PrivateKeyInfoFactory
                            .createPrivateKeyInfo(new ECPrivateKeyParameters(
                                    sharedPrivateKeyMap.getShare(keyID).getValue(), domainParams))
                            .getEncoded()));
            SubjectPublicKeyInfo pubKey = this.fetchPublicKey(keyID);

            // TODO: perhaps add CA cert and trust anchor to key store if available
            PKCS12SafeBagBuilder eeCertBagBuilder = new PKCS12SafeBagBuilder(
                    createCertificate(keyID, sharedPrivateKeyMap.getShare(keyID).getSequenceNo(),
                            (PrivateKey) nodeContext.getNodeCAStore().getKey("nodeCA", new char[0])));

            eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(keyID));

            SubjectKeyIdentifier pubKeyId = extUtils.createSubjectKeyIdentifier(pubKey);

            eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

            PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, encOut);

            keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(keyID));
            keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

            builder.addEncryptedData(
                    new JcePKCSPBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC)
                            .setProvider("BC").build(password),
                    new PKCS12SafeBag[] { eeCertBagBuilder.build() });

            builder.addData(keyBagBuilder.build());
        }

        PKCS12PfxPdu pfx = builder.build(new JcePKCS12MacCalculatorBuilder(NISTObjectIdentifiers.id_sha256),
                password);

        return pfx.getEncoded(ASN1Encoding.DL);
    } catch (PKCSException e) {
        throw new GeneralSecurityException("Unable to create key store: " + e.getMessage(), e);
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException("Unable to create operator: " + e.getMessage(), e);
    }
}