Example usage for org.bouncycastle.crypto BufferedBlockCipher BufferedBlockCipher

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

Introduction

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

Prototype

public BufferedBlockCipher(BlockCipher cipher) 

Source Link

Document

Create a buffered block cipher without padding.

Usage

From source file:br.com.elotech.karina.service.impl.GeradorSenhaElotech.java

@SneakyThrows
private String internalGenerate(String concatLicense) {

    System.out.println(concatLicense);

    String keyForSha1 = DigestUtils.md5Hex(KEY_ELOTECH).toUpperCase();
    System.out.println(keyForSha1);

    String keyForIdea = new String(Hex.encode(DigestUtils.getSha1Digest().digest(keyForSha1.getBytes())))
            .toUpperCase();/*from  ww w. ja v a 2s . c o m*/

    System.out.println(keyForIdea);

    byte[] input = concatLicense.getBytes();
    byte[] out = new byte[input.length];

    KeyParameter keyParameter = new KeyParameter(keyForIdea.getBytes());

    BufferedBlockCipher cipher = new BufferedBlockCipher(new IDEAEngine());

    cipher.init(true, keyParameter);

    cipher.processBytes(input, 0, input.length, out, 0);

    String ideaSecret = Base64.getEncoder().encodeToString(out);

    System.out.println(ideaSecret);

    return null;

}

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;//  w w w. j  a  v  a 2  s .  c  o  m
    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 w  ww .j a  v a2 s.  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.github.horrorho.inflatabledonkey.file.FileStreamWriter.java

License:Open Source License

static InputStream decryptStream(InputStream in, XFileKey keyCipher) {
    BlockCipher cipher = keyCipher.ciphers().get();
    cipher.init(false, new KeyParameter(keyCipher.key()));
    return new CipherInputStream(in, new BufferedBlockCipher(cipher));
}

From source file:com.github.horrorho.inflatabledonkey.pcs.xfile.BlockDecrypters.java

License:Open Source License

public static BlockDecrypter create(byte[] key) {
    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    SHA1Digest digest = new SHA1Digest();
    return create(cipher, digest, key);
}

From source file:com.github.horrorho.liquiddonkey.cloud.file.FileDecrypter.java

License:Open Source License

/**
 * Returns a new instance./*from w  w w . ja va2 s.c  o  m*/
 *
 * @return a new instance, not null
 */
public static FileDecrypter create() {
    return FileDecrypter.from(new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())), new SHA1Digest());
}

From source file:com.healthmarketscience.jackcess.impl.office.BlockCipherProvider.java

License:Apache License

@Override
protected BufferedBlockCipher getBlockCipher() {
    if (_cipher == null) {
        _cipher = new BufferedBlockCipher(initCipher());
    }/*ww  w .ja v a 2  s .  c o  m*/
    return _cipher;
}

From source file:com.licel.jcardsim.crypto.SymmetricCipherImpl.java

License:Apache License

private void selectCipherEngine(Key theKey) {
    if (theKey == null) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }//from ww w  .j  a  va2  s .c  om
    if (!theKey.isInitialized()) {
        CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY);
    }
    if (!(theKey instanceof SymmetricKeyImpl)) {
        CryptoException.throwIt(CryptoException.ILLEGAL_VALUE);
    }
    SymmetricKeyImpl key = (SymmetricKeyImpl) theKey;
    switch (algorithm) {
    case ALG_DES_CBC_NOPAD:
    case ALG_AES_BLOCK_128_CBC_NOPAD:
        engine = new BufferedBlockCipher(new CBCBlockCipher(key.getCipher()));
        break;
    case ALG_DES_CBC_ISO9797_M1:
        engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new ZeroBytePadding());
        break;
    case ALG_DES_CBC_ISO9797_M2:
        engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new ISO7816d4Padding());
        break;
    case ALG_DES_CBC_PKCS5:
        engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new PKCS7Padding());
        break;
    case ALG_DES_ECB_NOPAD:
    case ALG_AES_BLOCK_128_ECB_NOPAD:
        engine = new BufferedBlockCipher(key.getCipher());
        break;
    case ALG_DES_ECB_ISO9797_M1:
        engine = new PaddedBufferedBlockCipher(key.getCipher(), new ZeroBytePadding());
        break;
    case ALG_DES_ECB_ISO9797_M2:
        engine = new PaddedBufferedBlockCipher(key.getCipher(), new ISO7816d4Padding());
        break;
    case ALG_DES_ECB_PKCS5:
        engine = new PaddedBufferedBlockCipher(key.getCipher(), new PKCS7Padding());
        break;
    default:
        CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM);
        break;
    }
}

From source file:com.raphfrk.craftproxyclient.net.protocol.p16x.P16xProtocol.java

License:Open Source License

private void enableEncryption(PacketChannel server, PacketChannel client, byte[] serverSecret,
        byte[] clientSecret) {
    BufferedBlockCipher outServer = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8));
    BufferedBlockCipher inServer = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8));
    CipherParameters paramsServer = new ParametersWithIV(new KeyParameter(serverSecret), serverSecret);
    outServer.init(true, paramsServer);//ww  w.j ava  2 s  .co m
    inServer.init(false, paramsServer);

    BufferedBlockCipher outClient = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8));
    BufferedBlockCipher inClient = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8));
    CipherParameters paramsClient = new ParametersWithIV(new KeyParameter(clientSecret), clientSecret);
    outClient.init(true, paramsClient);
    inClient.init(false, paramsClient);

    client.setWrappedChannel(new CryptByteChannelWrapper(client.getRawChannel(), outClient, inClient));

    server.setWrappedChannel(new CryptByteChannelWrapper(server.getRawChannel(), outServer, inServer));
}

From source file:com.raphfrk.craftproxyclient.net.protocol.p17xlogin.P17xLoginProtocol.java

License:Open Source License

private void enableEncryption(PacketChannel server, PacketChannel client, byte[] secret) {
    BufferedBlockCipher out = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8));
    BufferedBlockCipher in = new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 8));
    CipherParameters params = new ParametersWithIV(new KeyParameter(secret), secret);
    out.init(true, params);//from   ww w  .java 2s . c  o m
    in.init(false, params);

    // Unencrypted
    client.setWrappedChannel(client.getRawChannel());

    // AES
    server.setWrappedChannel(new CryptByteChannelWrapper(server.getRawChannel(), out, in));
}