AES-GCM with arbitrary tag length

Viewed 819

For algorithm test vector evaluation, I am trying to perform an AES in GCM mode for encryption and decryption with arbitrary tag length values such as 32 bits.

When I try to initialize my cipher with such an arbitrary tag length as follows:

final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec parameterSpec = new GCMParameterSpec(tagLen, iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);

I am met with this error:

java.security.InvalidAlgorithmParameterException: Unsupported TLen value; must be one of {128, 120, 112, 104, 96}

Normally, this would be a good thing, because you don't want a tag length of 32. However, for my purposes I do need this tag length.

Is there a way that I can override these restrictions to allow for arbitrary tag lengths?

1 Answers

The Bouncy Castle library was created to support many algorithms in software, with the caveat that it let's you shoot yourself in the foot if you really want to.

I can run the above code with tag size 32 without issue:

Security.addProvider(new BouncyCastleProvider());

SecretKeySpec secretKey = new SecretKeySpec(new byte[16], "AES");

final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
GCMParameterSpec parameterSpec = new GCMParameterSpec(32, new byte[16]);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
cipher.update("Maarten did it".getBytes(StandardCharsets.UTF_8));
byte[] ct = cipher.doFinal();     

Note that the error can be seen e.g. here. As you can see that is the internal implementation of AES/GCM in the provider, not e.g. Cipher. You may have found that out by looking at the full stacktrace...

Related