Example usage for org.bouncycastle.crypto.modes CBCBlockCipher CBCBlockCipher

List of usage examples for org.bouncycastle.crypto.modes CBCBlockCipher CBCBlockCipher

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.modes CBCBlockCipher CBCBlockCipher.

Prototype

public CBCBlockCipher(BlockCipher cipher) 

Source Link

Document

Basic constructor.

Usage

From source file:com.vmware.admiral.common.security.EncryptorService.java

License:Open Source License

private BufferedBlockCipher getCipher(boolean forEncryption) {
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());
    cipher.init(forEncryption, new ParametersWithIV(
            new KeyParameter(keyBytes, IV_LENGTH, keyBytes.length - IV_LENGTH), keyBytes, 0, IV_LENGTH));
    return cipher;
}

From source file:com.wlami.mibox.core.encryption.AesEncryption.java

License:Open Source License

/**
 * Encrypts and decrypts a byte array.//from  w w  w. j  a va 2  s . c  o m
 * 
 * @param encrypt
 *            <code>true</code> for encryption <br/>
 *            <code>false</code> for decryption
 * @param ciphertext
 *            the data which shall be decrypted or encrypted
 * @param initVector
 *            the iv
 * @param key
 *            the key
 * @return an encrypted /decrypted byte array
 * @throws CryptoException
 */
public static byte[] crypt(boolean encrypt, byte[] ciphertext, byte[] initVector, byte[] key)
        throws InvalidCipherTextException {
    log.debug("starting " + (encrypt ? "encryption" : "decryption"));
    BlockCipher engine = new AESEngine();
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
    log.debug("retrieved an AESEngine");
    cipher.init(encrypt, new ParametersWithIV(new KeyParameter(key), initVector));
    byte[] cipherArray = new byte[cipher.getOutputSize(ciphertext.length)];
    log.debug("creatied cipherArray with size " + cipherArray.length + "\n encryption...");
    int outputByteCount = cipher.processBytes(ciphertext, 0, ciphertext.length, cipherArray, 0);
    log.debug("finalizing cipher");
    outputByteCount += cipher.doFinal(cipherArray, outputByteCount);
    byte[] result = new byte[outputByteCount];
    System.arraycopy(cipherArray, 0, result, 0, outputByteCount);
    return result;
}

From source file:com.zotoh.crypto.BCOfuscator.java

License:Open Source License

private String decrypt(String encrypted) throws Exception {
    if (isEmpty(encrypted)) {
        return encrypted;
    }//w  ww. j  av  a 2 s  .c  om
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
    byte[] p = Base64.decodeBase64(encrypted), out = new byte[1024];
    ByteOStream baos = new ByteOStream();
    int c;

    // initialise the cipher with the key bytes, for encryption
    cipher.init(false, new KeyParameter(getKey()));
    c = cipher.processBytes(p, 0, p.length, out, 0);
    if (c > 0) {
        baos.write(out, 0, c);
    }

    c = cipher.doFinal(out, 0);
    if (c > 0) {
        baos.write(out, 0, c);
    }

    return asString(baos.asBytes());
}

From source file:com.zotoh.crypto.BCOfuscator.java

License:Open Source License

private String encrypt(String clearText) throws Exception {
    if (isEmpty(clearText)) {
        return clearText;
    }/*from   w  ww  .  j  a va 2  s .c om*/
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
    ByteOStream baos = new ByteOStream();
    byte[] p = asBytes(clearText), out = new byte[4096];
    int c;

    // initialise the cipher with the key bytes, for encryption
    cipher.init(true, new KeyParameter(getKey()));
    c = cipher.processBytes(p, 0, p.length, out, 0);
    if (c > 0) {
        baos.write(out, 0, c);
    }

    c = cipher.doFinal(out, 0);
    if (c > 0) {
        baos.write(out, 0, c);
    }

    return Base64.encodeBase64String(baos.asBytes());
}

From source file:com._17od.upm.crypto.EncryptionService.java

License:Open Source License

public void initCipher(char[] password) throws InvalidPasswordException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, Exception {

    try {/*from w w  w. j  av a2 s  .  c o  m*/
        //Establishing Secure Channel
        SecureChannel(password);
        //SecureChannel();

        //Asking Card to be ready with Symm Key
        byte[] Data = new byte[password.length + salt.length];
        System.arraycopy(password.toString().getBytes(), 0, Data, 0, password.length);
        System.arraycopy(salt, 0, Data, password.length, salt.length);
        InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_GENKEY, (byte) 0,
                (byte) 0, Data);

        //Generate Nounce for PC
        N_1 = generateSalt();
        byte[] Temp = new byte[N_1.length + 16];
        System.arraycopy(N_1, 0, Temp, 0, N_1.length);
        System.arraycopy("AAAAAAAAAAAAAAAA".getBytes(), 0, Temp, N_1.length, 16);
        byte[] res = new byte[32];
        cipher.doFinal(Temp, 0, 32, res, 0);

        //Send Ek(Nounce_PC || ID of PC)
        ResponseFromCard = InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_N_1,
                (byte) 0, (byte) 0, res);

        //Received response from Card Nounce_PC || Nounce_Card || ID of Card

        //Decrypting Card Nounce
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] res1 = new byte[48];
        cipher.doFinal(ResponseFromCard, 0, 48, res1, 0);

        //Copying Nounce_PC
        byte[] res2 = new byte[16];
        System.arraycopy(res1, 0, res2, 0, 16);

        for (short i = 0; i < N_1.length; i++) {
            if (res2[i] != N_1[i]) {
                //If Nounce_PC is not matching throw error
                /*throw exception*/
                JOptionPane.showMessageDialog(mainWindow, Translator.translate("SecureChProblem"));
                System.exit(0);
            }
        }

        //Copying Nounce_Card
        System.arraycopy(res1, 16, N_B, 0, 16);

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        cipher.doFinal(N_B, 0, 16, res2, 0);

        //Send Ek(Nounce_Card) 
        ResponseFromCard = InterFaceApplet.SendAppletInstructionSecureChannel(PCSideCardInterface.SEND_INS_N_B,
                (byte) 0, (byte) 0, res2);
        //Checking response from card for Nounce_Card
        if (ResponseFromCard == null) {
            //If Nounce_Card is not matching throw error
            /*throw exception*/
            JOptionPane.showMessageDialog(mainWindow, Translator.translate("SecureChProblem"));
            System.exit(0);
        }
        //Nounce_Card is Verified, then Generate Session Key      
        byte[] SessionKey = new byte[16];
        System.arraycopy(N_1, 0, res, 0, 16);
        System.arraycopy(N_B, 0, res, 16, 16);

        //HASH(Nounce_PC || Nounce_Card)
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        SessionKey = Arrays.copyOf(sha.digest(res), 16);

        //Initialing AES with Session Key
        sessionKeySpec = new SecretKeySpec(SessionKey, "AES");

        SKcipher = Cipher.getInstance("AES/ECB/NOPADDING");

        SKcipher.init(Cipher.DECRYPT_MODE, sessionKeySpec);

        //For New Database
        if (FileHandle == null) {
            //Asking for Handle from Card            
            FileHandle = InterFaceApplet.SendAppletInstruction(PCSideCardInterface.SEND_INS_SETKEY, (byte) 0,
                    (byte) 0, null, password);
        }
        //Asking Key from Card
        byte[] KeyFromCard1 = InterFaceApplet.SendAppletInstruction(PCSideCardInterface.SEND_INS_GETKEY,
                (byte) 0, (byte) 0, FileHandle, password);

        //Extracting Key from Card           
        System.arraycopy(KeyFromCard1, (short) 0, KeyFromCard, (short) 0, (short) 1);
        //Decrypting the key using Session Key
        SKcipher.doFinal(KeyFromCard1, (short) 1, (short) (KeyFromCard1.length - 1), KeyFromCard, (short) 1);

    } catch (InvalidPasswordException ex) {
        throw ex;
    }

    //Encryption/Decryption operation        
    KeyParameter keyParams = new KeyParameter(Util.cutArray(KeyFromCard, FileHandle_LENGTH, KeyLengthAES));

    encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    encryptCipher.init(true, keyParams);
    decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    decryptCipher.init(false, keyParams);

}

From source file:common.crypto.bouncycastle.CCryptoAESBC.java

License:Open Source License

@Override
public void initialize(byte[] byaIV, byte[] byaKey, CryptoTypes.EBlockMode eMode,
        CryptoTypes.EKeyLength eKeyLen) {
    switch (eMode) {
    case CBC://from w  w w. java  2  s  .c  om
        m_blockCipher = new CBCBlockCipher(new AESLightEngine());
        break;
    }
    m_keyParam = new ParametersWithIV(new KeyParameter(byaKey), byaIV);
    m_nBlockSize = m_blockCipher.getBlockSize();
}

From source file:crypto.util.encription.Crypto.java

public Crypto(byte[] key) {
    /*/*  w  ww  .  j av a  2s. c o m*/
     cipher = new PaddedBlockCipher(
     new CBCBlockCipher(
     new DESEngine() ) );
     */

    cipher = new PaddedBlockCipher(new CBCBlockCipher(new BlowfishEngine()));

    this.key = new KeyParameter(key);
}

From source file:dbn.crypto.Crypto.java

public static byte[] aesEncrypt(byte[] plaintext, byte[] key) {
    try {//from   w  w  w. ja  va  2 s . c o m
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:dbn.crypto.Crypto.java

public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] key) {
    try {//from ww  w . j  av a2 s  . com
        if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ivCiphertext length");
        }
        byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

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  w  w.  j a  v  a  2  s .  c o m*/

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