Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES GCM implementation with authentication Tag in Java

I'm using AES GCM authentication in my android project and it works fine. But getting some issues with authentication tag when it compare with openssl API generate tag. Please find the java code below:

SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
byte[] iv = generateRandomIV();
IvParameterSpec ivspec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
int outputLength = cipher.getOutputSize(data.length); // Prepare output buffer
byte[] output = new byte[outputLength];
int outputOffset = cipher.update(data, 0, data.length, output, 0);// Produce cipher text
outputOffset += cipher.doFinal(output, outputOffset);

I am using openssl for the same in iOS and generating authentication tag using below code

NSMutableData* tag = [NSMutableData dataWithLength:tagSize];
EVP_CIPHER_CTX_ctrl(&ctx, EVP_CTRL_GCM_GET_TAG, [tag length], [tag mutableBytes])

In java or bouncy castle, not able to get the exact authentication tag which openssl return and can you help me to resolve this issue. Thanks

like image 919
user3656812 Avatar asked May 26 '14 06:05

user3656812


1 Answers

In Java the tag is unfortunately added at the end of the ciphertext. You can configure the size (in bits, using a multiple of 8) using GCMParameterSpec - it defaults to the full size of 128 bits otherwise. You can therefore grab the tag using Arrays.copyOfRange(ciphertext, ciphertext.length - (tagSize / Byte.SIZE), ciphertext.length) if you really want to.

It is unfortunate since the tag does not have to be put at the end, and it messes up the online nature of GCM decryption - requiring internal buffering instead of being able to directly return the plaintext. On the other hand, the tag is automatically verified during decryption.

like image 115
Maarten Bodewes Avatar answered Sep 30 '22 13:09

Maarten Bodewes