示例#1
0
  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);
    store.setKeyEntry(alias, keyPair.getPrivate(), pwd, chain);

    return store;
  }
  public static void genPKCS12File(OutputStream pfxOut, PrivateKey key, Certificate[] chain)
      throws Exception {

    OutputEncryptor encOut =
        new JcePKCSPBEOutputEncryptorBuilder(NISTObjectIdentifiers.id_aes256_CBC)
            .setProvider("BC")
            .build(KEY_PASSWD);

    PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder((X509Certificate) chain[2]);
    taCertBagBuilder.addBagAttribute(
        PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Bouncy Primary Certificate"));

    //		PKCS12SafeBagBuilder caCertBagBuilder = new
    // JcaPKCS12SafeBagBuilder((X509Certificate)chain[1]);
    //		caCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new
    // DERBMPString("Bouncy Intermediate Certificate"));

    PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder((X509Certificate) chain[0]);
    eeCertBagBuilder.addBagAttribute(
        PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key"));

    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    SubjectKeyIdentifier pubKeyId = extUtils.createSubjectKeyIdentifier(chain[0].getPublicKey());
    eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

    PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(key, encOut);
    keyBagBuilder.addBagAttribute(
        PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key"));
    keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId);

    PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder();
    builder.addData(keyBagBuilder.build());
    builder.addEncryptedData(
        new JcePKCSPBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC)
            .setProvider("BC")
            .build(KEY_PASSWD),
        new PKCS12SafeBag[] {
          eeCertBagBuilder.build(),
          // caCertBagBuilder.build(),
          taCertBagBuilder.build()
        });
    PKCS12PfxPdu pfx =
        builder.build(
            new JcePKCS12MacCalculatorBuilder(NISTObjectIdentifiers.id_sha256), KEY_PASSWD);
    // make sure we don't include indefinite length encoding
    pfxOut.write(pfx.getEncoded(ASN1Encoding.DL));
    pfxOut.close();
  }