Example usage for org.bouncycastle.crypto BlockCipher BlockCipher

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

Introduction

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

Prototype

BlockCipher

Source Link

Usage

From source file:org.panbox.core.crypto.io.AESGCMRandomAccessFileHW.java

License:Open Source License

@Override
protected void initCiphers() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        RandomDataGenerationException, InvalidAlgorithmParameterException, NoSuchProviderException {

    super.initCiphers();

    // TODO: This following code mixes the SunJCE AES blockcipher
    // implementation with Bouncycastle's GCMBlockCipher to improve
    // performance due to SunJCE's AES NI support. Replace this with
    // "native" BC code, as soon as they introduce AES NI support
    // themselves. For more information see
    // http://bouncy-castle.1462172.n4.nabble.com/Using-BC-AES-GCM-for-S3-td4657050.html
    this.gcmEngine = new GCMBlockCipher(new BlockCipher() {
        Cipher aes = Cipher.getInstance("AES/ECB/NoPadding", KeyConstants.PROV_SunJCE);

        public void reset() {
        }//from   w  ww  .  j av  a 2  s  . c om

        public int processBlock(byte[] in, int inOff, byte[] out, int outOff)
                throws DataLengthException, IllegalStateException {
            try {
                aes.update(in, outOff, getBlockSize(), out, outOff);
            } catch (ShortBufferException e) {
                throw new DataLengthException();
            }
            return getBlockSize();
        }

        public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException {
            KeyParameter kp = (KeyParameter) params;
            SecretKeySpec key = new SecretKeySpec(kp.getKey(), "AES");
            try {
                aes.init(forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key);
            } catch (InvalidKeyException e) {
                throw new IllegalArgumentException(e);
            }
        }

        public int getBlockSize() {
            return aes.getBlockSize();
        }

        public String getAlgorithmName() {
            return aes.getAlgorithm();
        }
    });
}