Example usage for org.bouncycastle.crypto.modes GCMBlockCipher processAADBytes

List of usage examples for org.bouncycastle.crypto.modes GCMBlockCipher processAADBytes

Introduction

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

Prototype

public void processAADBytes(byte[] in, int inOff, int len) 

Source Link

Usage

From source file:com.github.horrorho.inflatabledonkey.crypto.AESGCM.java

License:Open Source License

/**
 * Returns decrypted data./* w w  w . java  2 s.  co  m*/
 *
 * @param key
 * @param nonce nonce/ IV
 * @param header
 * @param encryptedData
 * @param tag
 * @param optional optional AADBytes (post header)
 * @return decrypted data
 * @throws IllegalArgumentException on decryption exceptions
 * @throws NullPointerException on null arguments
 */
public static byte[] decrypt(byte[] key, byte[] nonce, byte[] header, byte[] encryptedData, byte[] tag,
        Optional<byte[]> optional) {

    try {
        GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
        AEADParameters parameters = new AEADParameters(new KeyParameter(key), tag.length * 8, nonce, header);
        cipher.init(false, parameters);

        if (optional.isPresent()) {
            byte[] aadBytes = optional.get();
            cipher.processAADBytes(aadBytes, 0, aadBytes.length);
        }

        byte[] out = new byte[cipher.getOutputSize(encryptedData.length + tag.length)];

        int pos = cipher.processBytes(encryptedData, 0, encryptedData.length, out, 0);
        pos += cipher.processBytes(tag, 0, tag.length, out, pos);
        pos += cipher.doFinal(out, pos);

        return Arrays.copyOf(out, pos);

    } catch (IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalStateException("GCM decrypt error", ex);
    }
}