Example usage for org.bouncycastle.crypto.engines RC2Engine RC2Engine

List of usage examples for org.bouncycastle.crypto.engines RC2Engine RC2Engine

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.engines RC2Engine RC2Engine.

Prototype

RC2Engine

Source Link

Usage

From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastleStoreProvider.java

License:Open Source License

@Override
public byte[] encodePKCS12(X509Certificate[] crtChain, KeyPair key, PKCS10Object csr, X509CRL crl,
        PasswordCallback password, String resource) throws IOException, PasswordRequiredException {
    String passwordInput = (password != null ? password.queryPassword(resource) : null);

    if (password != null && passwordInput == null) {
        throw new PasswordRequiredException("Password input cancelled while writing PKCS#12 file");
    }//w ww.j a  va  2 s . c  om

    PKCS12SafeBagBuilder[] crtBagBuilders = new PKCS12SafeBagBuilder[crtChain != null ? crtChain.length : 0];
    DERBMPString crt0FriendlyName = null;
    SubjectKeyIdentifier subjectKeyIdentifier = null;

    if (crtChain != null) {
        int crtIndex = 0;

        for (X509Certificate crt : crtChain) {
            PKCS12SafeBagBuilder crtBagBuilder = crtBagBuilders[crtIndex] = new JcaPKCS12SafeBagBuilder(crt);
            DERBMPString crtFriendlyName = new DERBMPString(crt.getSubjectX500Principal().toString());

            crtBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, crtFriendlyName);
            if (crtIndex == 0) {
                crt0FriendlyName = crtFriendlyName;
                try {
                    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();

                    subjectKeyIdentifier = extensionUtils.createSubjectKeyIdentifier(crt.getPublicKey());
                } catch (NoSuchAlgorithmException e) {
                    throw new StoreProviderException(e);
                }
            }
            crtIndex++;
        }
    }

    PKCS12SafeBagBuilder keyBagBuilder = null;

    if (key != null) {
        if (passwordInput != null) {
            BcPKCS12PBEOutputEncryptorBuilder keyBagEncryptorBuilder = new BcPKCS12PBEOutputEncryptorBuilder(
                    PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC,
                    new CBCBlockCipher(new DESedeEngine()));
            OutputEncryptor keyBagEncrypter = keyBagEncryptorBuilder.build(passwordInput.toCharArray());

            keyBagBuilder = new JcaPKCS12SafeBagBuilder(key.getPrivate(), keyBagEncrypter);
        } else {
            keyBagBuilder = new JcaPKCS12SafeBagBuilder(key.getPrivate());
        }
        if (crtBagBuilders.length > 0) {
            crtBagBuilders[0].addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, subjectKeyIdentifier);
            keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, subjectKeyIdentifier);
            keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, crt0FriendlyName);
        }
    }

    PKCS12SafeBag[] crtBags = new PKCS12SafeBag[crtBagBuilders.length];
    int crtBagIndex = 0;

    for (PKCS12SafeBagBuilder crtBagBuilder : crtBagBuilders) {
        crtBags[crtBagIndex] = crtBagBuilder.build();
        crtBagIndex++;
    }

    PKCS12PfxPduBuilder pkcs12Builder = new PKCS12PfxPduBuilder();

    if (passwordInput != null) {
        BcPKCS12PBEOutputEncryptorBuilder crtBagEncryptorBuilder = new BcPKCS12PBEOutputEncryptorBuilder(
                PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC, new CBCBlockCipher(new RC2Engine()));
        OutputEncryptor crtBagEncryptor = crtBagEncryptorBuilder.build(passwordInput.toCharArray());

        pkcs12Builder.addEncryptedData(crtBagEncryptor, crtBags);
    } else {
        for (PKCS12SafeBag crtBag : crtBags) {
            pkcs12Builder.addData(crtBag);
        }
    }
    if (keyBagBuilder != null) {
        pkcs12Builder.addData(keyBagBuilder.build());
    }

    PKCS12PfxPdu pkcs12;

    try {
        if (passwordInput != null) {
            pkcs12 = pkcs12Builder.build(new BcPKCS12MacCalculatorBuilder(), passwordInput.toCharArray());
        } else {
            pkcs12 = pkcs12Builder.build(null, null);
        }
    } catch (PKCSException e) {
        throw new StoreProviderException(e);
    }
    return pkcs12.getEncoded();
}

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 v a  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:org.cryptacular.spec.BlockCipherSpec.java

License:Open Source License

@Override
public BlockCipher newInstance() {
    BlockCipher cipher;/*  w  ww.  j  a  v  a 2 s  .c om*/
    if ("AES".equalsIgnoreCase(algorithm)) {
        cipher = new AESFastEngine();
    } else if ("Blowfish".equalsIgnoreCase(algorithm)) {
        cipher = new BlowfishEngine();
    } else if ("Camellia".equalsIgnoreCase(algorithm)) {
        cipher = new CamelliaEngine();
    } else if ("CAST5".equalsIgnoreCase(algorithm)) {
        cipher = new CAST5Engine();
    } else if ("CAST6".equalsIgnoreCase(algorithm)) {
        cipher = new CAST6Engine();
    } else if ("DES".equalsIgnoreCase(algorithm)) {
        cipher = new DESEngine();
    } else if ("DESede".equalsIgnoreCase(algorithm) || "DES3".equalsIgnoreCase(algorithm)) {
        cipher = new DESedeEngine();
    } else if ("GOST".equalsIgnoreCase(algorithm) || "GOST28147".equals(algorithm)) {
        cipher = new GOST28147Engine();
    } else if ("Noekeon".equalsIgnoreCase(algorithm)) {
        cipher = new NoekeonEngine();
    } else if ("RC2".equalsIgnoreCase(algorithm)) {
        cipher = new RC2Engine();
    } else if ("RC5".equalsIgnoreCase(algorithm)) {
        cipher = new RC564Engine();
    } else if ("RC6".equalsIgnoreCase(algorithm)) {
        cipher = new RC6Engine();
    } else if ("SEED".equalsIgnoreCase(algorithm)) {
        cipher = new SEEDEngine();
    } else if ("Serpent".equalsIgnoreCase(algorithm)) {
        cipher = new SerpentEngine();
    } else if ("Skipjack".equalsIgnoreCase(algorithm)) {
        cipher = new SkipjackEngine();
    } else if ("TEA".equalsIgnoreCase(algorithm)) {
        cipher = new TEAEngine();
    } else if ("Twofish".equalsIgnoreCase(algorithm)) {
        cipher = new TwofishEngine();
    } else if ("XTEA".equalsIgnoreCase(algorithm)) {
        cipher = new XTEAEngine();
    } else {
        throw new IllegalStateException("Unsupported cipher algorithm " + algorithm);
    }
    return cipher;
}

From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java

License:LGPL

private static PrivateKey derivePrivateKeyPBES2(EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId,
        char[] password) throws GeneralSecurityException, InvalidCipherTextException {
    PBES2Parameters pbeParams = PBES2Parameters.getInstance((ASN1Sequence) algId.getParameters());
    CipherParameters cipherParams = extractPBES2CipherParams(password, pbeParams);

    EncryptionScheme scheme = pbeParams.getEncryptionScheme();
    BufferedBlockCipher cipher;/*  ww  w.  ja  v a2  s. c o m*/
    if (scheme.getAlgorithm().equals(PKCSObjectIdentifiers.RC2_CBC)) {
        RC2CBCParameter rc2Params = RC2CBCParameter.getInstance(scheme);
        byte[] iv = rc2Params.getIV();
        CipherParameters param = new ParametersWithIV(cipherParams, iv);
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC2Engine()));
        cipher.init(false, param);
    } else {
        byte[] iv = ((ASN1OctetString) scheme.getObject()).getOctets();
        // this version, done for BC 1.49 compat, caused #1238.
        //            byte[] iv = ASN1OctetString.getInstance(scheme).getOctets();
        CipherParameters param = new ParametersWithIV(cipherParams, iv);
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
        cipher.init(false, param);
    }

    byte[] data = eIn.getEncryptedData();
    byte[] out = new byte[cipher.getOutputSize(data.length)];
    int len = cipher.processBytes(data, 0, data.length, out, 0);
    len += cipher.doFinal(out, len);
    byte[] pkcs8 = new byte[len];
    System.arraycopy(out, 0, pkcs8, 0, len);
    KeyFactory fact = KeyFactory.getInstance("RSA"); // It seems to work for both RSA and DSA.
    return fact.generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
}

From source file:org.xwiki.crypto.cipher.internal.symmetric.factory.BcRc2CbcPaddedCipherFactory.java

License:Open Source License

@Override
protected BlockCipher getEngineInstance() {
    return new RC2Engine();
}