简体   繁体   中英

Usage of additional authenticated data & authentication tag for AES-GCM using BouncyCastle

We are planning to use "AES/GCM/NoPadding" in Java using BouncyCastle v1.51. Can someone shed some light on the ideal implementation / best practices with respect to the usage & generation of additional authenticated data (AAD) & authentication tag?

  1. At what point should AAD be used in the encryption process?
  2. As per documentation, the authentication tag is part of encrypted output. In what format is it appended to the encrypted output?
  3. How is the authentication tag processed during decryption?

Following is the encryption code:

private static byte[] encryptGCM(byte[] plaintext,
        byte[] randomKeyBytes, byte[] randomIvBytes) throws Exception{
    SecretKey randomKey = new SecretKeySpec(randomKeyBytes, "AES");
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", new BouncyCastleProvider());
    cipher.init(Cipher.ENCRYPT_MODE, randomKey, new IvParameterSpec(
            randomIvBytes));    //TODO: here IvParamSpec could also be gcmP   = new GCMParameterSpec(12, keys, 32, 12); 

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, cipher);
    cipherOutputStream.write(plaintext);
    cipherOutputStream.close();
    return byteArrayOutputStream.toByteArray();//this is the encrypted text
}

I'll answer the questions in order:

  1. AAD does not have to be used at all, the IV is already included in GCM mode encryption. For GCM you should always specify the AAD before any plaintext. Bouncy Castle does handle an update of AAD later on, but doing so requires modular exponentiation. In other words, it may significantly slow down the encryption operation.
  2. The leftmost bits of the total tag are used, without any specific formatting. The bits (or, more precisely, bytes) are just appended to the ciphertext. Note that this is not specified this way for the algorithm, appending the tag is just an ad-hoc standard.
  3. A full block of ciphertext is buffered and not returned as plaintext during decryption, in case it contains the tag. On doFinal the right amount of bytes is taken from the ciphertext and interpreted as being the tag, and the last part of the plaintext is output. Note that the buffering of ciphertext is implementation specific, but the way that Cipher has been defined, some buffering has to take place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM