Example usage for org.bouncycastle.crypto BufferedBlockCipher doFinal

List of usage examples for org.bouncycastle.crypto BufferedBlockCipher doFinal

Introduction

In this page you can find the example usage for org.bouncycastle.crypto BufferedBlockCipher doFinal.

Prototype

public int doFinal(byte[] out, int outOff)
        throws DataLengthException, IllegalStateException, InvalidCipherTextException 

Source Link

Document

Process the last block in the buffer.

Usage

From source file:ch.dissem.bitmessage.cryptography.bc.BouncyCryptography.java

License:Apache License

@Override
public byte[] crypt(boolean encrypt, byte[] data, byte[] key_e, byte[] initializationVector) {
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
            new PKCS7Padding());
    CipherParameters params = new ParametersWithIV(new KeyParameter(key_e), initializationVector);

    cipher.init(encrypt, params);//from  w  w  w  .j  a  v  a 2s.c om

    byte[] buffer = new byte[cipher.getOutputSize(data.length)];
    int length = cipher.processBytes(data, 0, data.length, buffer, 0);
    try {
        length += cipher.doFinal(buffer, length);
    } catch (InvalidCipherTextException e) {
        throw new IllegalArgumentException(e);
    }
    if (length < buffer.length) {
        return Arrays.copyOfRange(buffer, 0, length);
    }
    return buffer;
}

From source file:co.rsk.crypto.KeyCrypterAes.java

License:Open Source License

/**
 * Password based encryption using AES - CBC 256 bits.
 *//* w  w w . ja  va  2  s.c o m*/
@Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter key) {
    checkNotNull(plainBytes);
    checkNotNull(key);

    try {
        // Generate iv - each encryption call has a different iv.
        byte[] iv = new byte[BLOCK_LENGTH];
        secureRandom.nextBytes(iv);

        ParametersWithIV keyWithIv = new ParametersWithIV(key, iv);

        // Encrypt using AES.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        cipher.init(true, keyWithIv);
        byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
        final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
        final int length2 = cipher.doFinal(encryptedBytes, length1);

        return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
    } catch (Exception e) {
        throw new KeyCrypterException("Could not encrypt bytes.", e);
    }
}

From source file:co.rsk.crypto.KeyCrypterAes.java

License:Open Source License

/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param dataToDecrypt    The data to decrypt
 * @param key              The AES key to use for decryption
 * @return                 The decrypted bytes
 * @throws                 KeyCrypterException if bytes could not be decrypted
 *///w w w.  ja v a 2s.com
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter key) {
    checkNotNull(dataToDecrypt);
    checkNotNull(key);

    try {
        ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(key.getKey()),
                dataToDecrypt.initialisationVector);

        // Decrypt the message.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
        cipher.init(false, keyWithIv);

        byte[] cipherBytes = dataToDecrypt.encryptedBytes;
        byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
        final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
        final int length2 = cipher.doFinal(decryptedBytes, length1);

        return Arrays.copyOf(decryptedBytes, length1 + length2);
    } catch (Exception e) {
        throw new KeyCrypterException("Could not decrypt bytes", e);
    }
}

From source file:cologne.eck.dr.op.crypto.password_hashing.Battcrypt_v0.java

License:Open Source License

@Override
public byte[] hashPassword(int outlen, byte[] in, byte[] salt, int t_cost, int m_cost, Object... varArgs)
        throws DataLengthException, IllegalStateException, InvalidCipherTextException {

    SHA512Digest sha = new SHA512Digest();
    int[] data = new int[DATA_SIZE_INT];
    BlowfishEngine blowfish;//from   w ww .  ja  v a2  s.  c  om
    long upgradeLoops = 1;
    long loops;
    int memSize = 4 << m_cost;//= 4 * 2 ** m_cost
    int memMask = memSize - 1;
    int[] mem;

    byte[] hashBuffer = new byte[HASH_LENGTH_BYTE];// holds hash value as bytes
    byte[] dataBuffer = new byte[DATA_SIZE_BYTE];// holds encrypted bytes

    // These are the PHP max. values 
    if (m_cost > 18 || // maximum: 2.147.483.648 bytes
            (t_cost & 0xffff) > 62 || (t_cost >> 16) > 63 || outlen > HASH_LENGTH_BYTE) {
        throw new IllegalArgumentException("invalid parameters");
    }

    int tmp = t_cost >> 16;

    if (tmp != 0) {
        // upgradeLoops = 1, 2, 3, 4, 6, 8, 12, 16, ...
        upgradeLoops = (long) (3 - (tmp & 1)) << ((tmp - 1) >> 1);
    }

    // loops = 2, 3, 4, 6, 8, 12, 16, ...
    tmp = t_cost & 0xffff;
    loops = (long) ((tmp & 1) + 2) << (tmp >> 1);

    // key = SHA512(SHA512(salt) || in)
    byte[] keyBytes = new byte[HASH_LENGTH_BYTE];
    sha.update(salt, 0, salt.length);
    sha.doFinal(keyBytes, 0);
    sha.reset();
    sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
    sha.update(in, 0, in.length);//password
    sha.doFinal(keyBytes, 0);
    sha.reset();
    if (wipePassword == true) {
        Arrays.fill(in, (byte) 0);
    }

    // initialize cipher with 448 bit (56 byte) key: 
    // truncate keyBytes:
    byte[] blowfishKey = new byte[56];
    System.arraycopy(keyBytes, 0, blowfishKey, 0, 56);
    // use zeros as IV
    byte[] iv = new byte[IV_LENGTH_BYTE];
    KeyParameter params = new KeyParameter(blowfishKey);
    Arrays.fill(blowfishKey, (byte) 0);
    ParametersWithIV ivParams = new ParametersWithIV(params, iv);
    blowfish = new BlowfishEngine();
    // CBC, no padding: all vectors are multiples of Blowfish block length
    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(blowfish));
    cipher.init(true, ivParams);

    // initialize memory-hard vector:
    mem = new int[DATA_SIZE_INT * memSize];

    for (long u = 0; u < upgradeLoops; u++) {

        // initialize data:
        // data = SHA512(BIG_ENDIAN_64( 0) || key) || ...
        // ... || SHA512(BIG_ENDIAN_64(31) || key)         
        byte[] counterBytesBE = new byte[8]; // holds counter as long to update
        for (int i = 0; i < DATA_SIZE_BYTE / HASH_LENGTH_BYTE; i++) {

            counterBytesBE[7] = (byte) i; // set first byte
            sha.update(counterBytesBE, 0, counterBytesBE.length); // BIG_ENDIAN_64(i)
            sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
            sha.doFinal(hashBuffer, 0);
            sha.reset();
            // hash values allow weak garbage collector attack - 
            // so, avoid new allocations:             
            for (int j = 0; j < HASH_LENGTH_BYTE / 4; j++) {
                data[HASH_LENGTH_INT * i + j] = ((hashBuffer[j * 4 + 3] & 0xFF) << 24)
                        | ((hashBuffer[j * 4 + 2] & 0xFF) << 16) | ((hashBuffer[j * 4 + 1] & 0xFF) << 8)
                        | (hashBuffer[j * 4 + 0] & 0xFF); // little endian order
            }
            Arrays.fill(hashBuffer, (byte) 0);
        }

        // Initialize memory:
        for (int i = 0; i < memSize; i++) {
            // data = blowfish_encrypt_cbc(data)
            // mem = mem || data            
            for (int j = 0; j < DATA_SIZE_INT; j++) {
                dataBuffer[j * 4 + 0] = (byte) (data[j]);// little endian
                dataBuffer[j * 4 + 1] = (byte) (data[j] >>> 8);
                dataBuffer[j * 4 + 2] = (byte) (data[j] >>> 16);
                dataBuffer[j * 4 + 3] = (byte) (data[j] >>> 24);
            }
            int len = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);
            cipher.doFinal(dataBuffer, len);
            cipher.reset();

            // get iv for next encryption step:
            // "running CBC": the last block of the
            //  previous call is the IV for the next call
            System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);
            ivParams = new ParametersWithIV(params, iv);
            cipher.init(true, ivParams);

            for (int j = 0; j < DATA_SIZE_INT; j++) {
                data[j] = ((dataBuffer[j * 4 + 3] & 0xFF) << 24) | ((dataBuffer[j * 4 + 2] & 0xFF) << 16)
                        | ((dataBuffer[j * 4 + 1] & 0xFF) << 8) | (dataBuffer[j * 4 + 0] & 0xFF); // little endian order
            }
            System.arraycopy(data, 0, mem, DATA_SIZE_INT * i, DATA_SIZE_INT);
        }

        // encrypt data:
        for (int j = 0; j < DATA_SIZE_INT; j++) {
            dataBuffer[j * 4 + 0] = (byte) (data[j]);// little endian
            dataBuffer[j * 4 + 1] = (byte) (data[j] >>> 8);
            dataBuffer[j * 4 + 2] = (byte) (data[j] >>> 16);
            dataBuffer[j * 4 + 3] = (byte) (data[j] >>> 24);
        }
        int len = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);
        cipher.doFinal(dataBuffer, len);
        cipher.reset();
        System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);
        ivParams = new ParametersWithIV(params, iv);
        cipher.init(true, ivParams);

        for (int j = 0; j < DATA_SIZE_INT; j++) {
            data[j] = ((dataBuffer[j * 4 + 3] & 0xFF) << 24) | ((dataBuffer[j * 4 + 2] & 0xFF) << 16)
                    | ((dataBuffer[j * 4 + 1] & 0xFF) << 8) | (dataBuffer[j * 4 + 0] & 0xFF); // little endian order
        }

        // work:
        for (long i = 0; i < loops; i++) {
            for (int j = 0; j < memSize; j++) {
                // in the C++ reference implementation and the paper 
                // this rValue a 64 bit integer, but this makes only a
                // difference for memSize > 0xFFFFFFFF +1, while the
                // recommended maximum for memSize is 2^32
                int rValue = ((((int) data[DATA_SIZE_INT - 1]) << 24) & 0xff000000)
                        | ((((int) data[DATA_SIZE_INT - 1]) << 8) & 0x00ff0000)
                        | ((((int) data[DATA_SIZE_INT - 1]) >>> 8) & 0x0000ff00)
                        | ((((int) data[DATA_SIZE_INT - 1]) >>> 24) & 0x000000ff);
                int index = (int) (DATA_SIZE_INT * (rValue & memMask));

                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    mem[j * DATA_SIZE_INT + k] ^= data[k] ^ mem[index + k];
                }

                // convert to byte: 
                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    dataBuffer[k * 4 + 0] = (byte) (mem[j * DATA_SIZE_INT + k]);
                    dataBuffer[k * 4 + 1] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 8);
                    dataBuffer[k * 4 + 2] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 16);
                    dataBuffer[k * 4 + 3] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 24);
                }
                int len1 = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);

                cipher.doFinal(dataBuffer, len1);
                cipher.reset();
                // get iv for next step:
                System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);

                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    mem[j * DATA_SIZE_INT + k] = ((dataBuffer[k * 4 + 3] & 0xFF) << 24)
                            | ((dataBuffer[k * 4 + 2] & 0xFF) << 16) | ((dataBuffer[k * 4 + 1] & 0xFF) << 8)
                            | (dataBuffer[k * 4 + 0] & 0xFF); // little endian order
                }

                ivParams = new ParametersWithIV(params, iv);
                cipher.init(true, ivParams);

                // data ^= mem[j]
                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    data[k] ^= mem[DATA_SIZE_INT * j + k];
                }
            }
        }
        // Finish
        // key = truncate(SHA512(SHA512(data || key)), outlen) || zeros(HASH_LENGTH - outlen)
        // convert to byte: 
        for (int k = 0; k < DATA_SIZE_INT; k++) {
            dataBuffer[k * 4 + 0] = (byte) (data[k]);
            dataBuffer[k * 4 + 1] = (byte) (data[k] >>> 8);
            dataBuffer[k * 4 + 2] = (byte) (data[k] >>> 16);
            dataBuffer[k * 4 + 3] = (byte) (data[k] >>> 24);
        }
        sha.update(dataBuffer, 0, DATA_SIZE_BYTE);
        sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
        sha.doFinal(keyBytes, 0);
        sha.reset();
    }

    sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
    sha.doFinal(keyBytes, 0);
    sha.reset();

    byte[] out = new byte[outlen];

    System.arraycopy(keyBytes, 0, out, 0, out.length);

    // Clean-up:
    Arrays.fill(keyBytes, (byte) 0);
    Arrays.fill(dataBuffer, (byte) 0);
    Arrays.fill(iv, (byte) 0);
    Arrays.fill(data, 0);
    Arrays.fill(mem, (byte) 0);

    // wipe the key from parameters
    Arrays.fill(params.getKey(), (byte) 0);

    // prevent dead code eliminations (compiler optimizations):
    if ((keyBytes[HASH_LENGTH_BYTE - 1] | blowfishKey[blowfishKey.length - 1] | dataBuffer[DATA_SIZE_BYTE - 1]
            | hashBuffer[HASH_LENGTH_BYTE - 1] | data[DATA_SIZE_INT - 1] | iv[IV_LENGTH_BYTE - 1]
            | mem[mem.length - 1] | params.getKey()[params.getKey().length - 1]) != 0) {
        System.err.print("zeroization failed!");
    }
    if ((wipePassword == true) && (in[in.length - 1] != 0)) {
        System.err.print("zeroization failed!");
    }
    return out;
}

From source file:cologne.eck.peafactory.crypto.CipherStuff.java

License:Open Source License

/**
 * Encrypt/decrypt an array of bytes. This function is only used to 
 * encrypt the session key/*from ww w  .ja  va 2s.c o m*/
 * 
 * @param forEncryption - true for encryption, false for decryption
 * @param input         - plain text or cipher text
 * @param key         - the cryptographic key for the cipher
 * @param zeroize      - fills the key with 0 for true (when the key is no longer used)
 * @return            - plain text or cipher text
 */
public final static byte[] processCTR(boolean forEncryption, byte[] input, byte[] key, boolean zeroize) {
    //Help.printBytes("key",  input);
    KeyParameter kp = new KeyParameter(key);
    if (zeroize == true) {
        Zeroizer.zero(key);
    }

    byte[] iv = null;

    if (forEncryption == false) {
        // input is ciphertext, IV is stored on top of ciphertext
        // get IV:
        iv = new byte[CipherStuff.getCipherAlgo().getBlockSize()];
        System.arraycopy(input, 0, iv, 0, iv.length);
        // truncate ciphertext:
        byte[] tmp = new byte[input.length - iv.length];
        System.arraycopy(input, iv.length, tmp, 0, tmp.length);
        input = tmp;
    } else {
        // input is plaintext
        iv = new RandomStuff().createRandomBytes(CipherStuff.getCipherAlgo().getBlockSize());
    }
    ParametersWithIV ivp = new ParametersWithIV(kp, iv);

    BufferedBlockCipher b = new BufferedBlockCipher(new SICBlockCipher(cipherAlgo));

    b.init(true, ivp);
    byte[] out = new byte[input.length];

    int len = b.processBytes(input, 0, input.length, out, 0);

    try {
        len += b.doFinal(out, len);
    } catch (DataLengthException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidCipherTextException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Zeroizer.zero(kp.getKey());

    if (forEncryption == false) {// decryption: output plaintext
        return out;
    } else { // encryption: output (IV || ciphertext)
        Zeroizer.zero(input);
        // store IV on top of ciphertext
        byte[] tmp = new byte[out.length + iv.length];
        System.arraycopy(iv, 0, tmp, 0, iv.length);
        System.arraycopy(out, 0, tmp, iv.length, out.length);
        return tmp;
    }
}

From source file:com.android.isoma.enc.Encryption.java

License:Open Source License

public byte[] callCipher(BufferedBlockCipher cipher, byte[] data)
        throws DataLengthException, IllegalStateException, InvalidCipherTextException {
    int size = cipher.getOutputSize(data.length);
    byte[] result = new byte[size];
    int olen = cipher.processBytes(data, 0, data.length, result, 0);

    int last = cipher.doFinal(result, olen);

    final byte[] plain = new byte[olen + last];
    System.arraycopy(result, 0, plain, 0, plain.length);
    // cipher.reset();
    return plain;

}

From source file:com.completetrsst.crypto.Crypto.java

License:Apache License

private static byte[] process(byte[] input, BufferedBlockCipher bufferedBlockCipher,
        CipherParameters cipherParameters, boolean forEncryption) throws InvalidCipherTextException {
    bufferedBlockCipher.init(forEncryption, cipherParameters);

    int inputOffset = 0;
    int inputLength = input.length;

    int maximumOutputLength = bufferedBlockCipher.getOutputSize(inputLength);
    byte[] output = new byte[maximumOutputLength];
    int outputOffset = 0;
    int outputLength = 0;

    int bytesProcessed;

    bytesProcessed = bufferedBlockCipher.processBytes(input, inputOffset, inputLength, output, outputOffset);
    outputOffset += bytesProcessed;/*w  w  w .j a v  a2s .co m*/
    outputLength += bytesProcessed;

    bytesProcessed = bufferedBlockCipher.doFinal(output, outputOffset);
    outputOffset += bytesProcessed;
    outputLength += bytesProcessed;

    if (outputLength == output.length) {
        return output;
    } else {
        byte[] truncatedOutput = new byte[outputLength];
        System.arraycopy(output, 0, truncatedOutput, 0, outputLength);
        return truncatedOutput;
    }
}

From source file:com.foilen.smalltools.crypt.AbstractBufferedBlockCipherCrypt.java

License:Open Source License

private byte[] finalize(BufferedBlockCipher bufferedBlockCipher, byte[] out, int outOff)
        throws DataLengthException, IllegalStateException, InvalidCipherTextException {
    outOff += bufferedBlockCipher.doFinal(out, outOff);
    if (outOff != out.length) {
        out = Arrays.copyOfRange(out, 0, outOff);
    }/*from   w  w  w. ja  v a 2 s.  co  m*/
    return out;
}

From source file:com.giacomodrago.immediatecrypt.aes.AESFacadeImpl.java

License:Open Source License

@Override
public AESEncryptedMessage encrypt(byte[] plaintext, String password) throws EncryptionException {

    // Check password is not empty
    if (password.isEmpty()) {
        throw new EncryptionException("Password is empty.");
    }//from w w  w . j a  v  a2s  .  c om

    // Generate random password salt
    String salt = RandomStringUtils.randomAlphanumeric(SALT_LENGTH);

    ParametersWithIV params = createEncryptionParameters(password, salt);
    byte[] iv = params.getIV();

    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    cipher.init(true, params);

    byte[] ciphertext = new byte[cipher.getOutputSize(plaintext.length)];

    int outputLen = cipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0);
    try {
        cipher.doFinal(ciphertext, outputLen);
    } catch (DataLengthException ex) {
        throw new EncryptionException(ex);
    } catch (IllegalStateException ex) {
        throw new EncryptionException(ex);
    } catch (InvalidCipherTextException ex) {
        throw new EncryptionException(ex);
    }

    return new AESEncryptedMessage(salt, iv, ciphertext);

}

From source file:com.giacomodrago.immediatecrypt.aes.AESFacadeImpl.java

License:Open Source License

@Override
public byte[] decrypt(AESEncryptedMessage encryptedMessage, String password) throws EncryptionException {

    byte[] ciphertext = encryptedMessage.getCiphertext();
    String salt = encryptedMessage.getSalt();
    byte[] iv = encryptedMessage.getIv();

    ParametersWithIV params = createDecryptionParameters(password, salt, iv);

    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));

    try {/* w w w .ja va2  s. c o m*/
        cipher.init(false, params);
    } catch (IllegalArgumentException ex) {
        throw new EncryptionException(ex);
    }

    byte[] plaintext = new byte[cipher.getOutputSize(ciphertext.length)];

    int outputLen = cipher.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0);
    try {
        cipher.doFinal(plaintext, outputLen);
    } catch (DataLengthException ex) {
        throw new EncryptionException(ex);
    } catch (IllegalStateException ex) {
        throw new EncryptionException(ex);
    } catch (InvalidCipherTextException ex) {
        throw new EncryptionException(ex);
    }

    return plaintext;

}