Incorrect key detection using AES / GCM in JAVA

I use AES to encrypt / decrypt some files in GCM mode using BouncyCastle.
While I am proving the wrong decryption key, there is no exception.
How to check that the key is wrong? my code is:

  SecretKeySpec incorrectKey = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC"); byte[] block = new byte[1048576]; int i; cipher.init(Cipher.DECRYPT_MODE, incorrectKey, ivSpec); BufferedInputStream fis=new BufferedInputStream(new ProgressMonitorInputStream(null,"Decrypting ...",new FileInputStream("file.enc"))); BufferedOutputStream ro=new BufferedOutputStream(new FileOutputStream("file_org")); CipherOutputStream dcOut = new CipherOutputStream(ro, cipher); while ((i = fis.read(block)) != -1) { dcOut.write(block, 0, i); } dcOut.close(); fis.close(); 

thanks

+3
java cryptography bouncycastle jce aes-gcm
source share
2 answers

There is no way to detect the wrong key in GCM mode. What you can verify is the authentication tag authentication, which means you used the correct key. The problem is that if the authentication tag is incorrect, it can indicate each of the following (or a combination of all, up to the complete replacement of the ciphertext tag and authentication):

  • Invalid key used
  • encrypted data in counter mode was changed during transportation;
  • Additional authenticated data has been changed.
  • The authentication tag itself was changed during the migration.

What you can do is send additional data to identify the private key. It can be a readable identifier ( "encryption-key-1" ), but it can also be a KCV value, a key verification value. KCV usually consists of a null block encrypted with a key, or a cryptographically secure hash above the key (also called a fingerprint). Since encryption using zero block leak information should not be used to identify the encryption key.

In fact, you can use the AAD function for GCM mode to calculate the authentication tag from the key's identity. Please note that you cannot distinguish between a compromised fingerprint and the use of the wrong key. However, it is less likely that the fingerprint is accidentally damaged than the entire structure of the IV, AAD, encrypted text, and authentication tags.

+4
source share

You are using NoPadding . Change this to PKCS7Padding for encryption and decryption. If the wrong key is used, the padding will almost certainly not decrypt as expected, and there will be an InvalidCipherTextException .

-6
source share

All Articles