I'm using AES to encrypt/decrypt some files in GCM mode using BouncyCastle.
While I'm proving wrong key for decryption there is no exception.
How should I check that the key is incorrect?
my code is this:

It would be very nice if you would accept some more answers and followup on your questions 4r1y4n (that would be Ariyan I suppose)
– Maarten BodewesSep 12 '12 at 20:33

1

Is there a specific reason why you don't accept answers on the encryption questions, 4r1y4n, or did they just escape your attention? You haven't accepted on any 4 in a row.
– Maarten BodewesSep 17 '12 at 23:35

2 Answers
2

There is no method that you can detect incorrect key in GCM mode. What you can check is if the authentication tag validates, which means you were using the right key. The problem is that if the authentication tag is incorrect then this could indicate each of the following (or a combination of all, up to and including the full replacement of the ciphertext and authentication tag):

an incorrect key is being used;

the counter mode encrypted data was altered during transport;

the additional authenticated data was altered;

the authentication tag itself was altered during transport.

What you could do is send additional data to identify the secret key used. This could be a readable identifier ("encryption-key-1") but it could also be a KCV, a key check value. A KCV normally consists of a zero-block encrypted with the key, or a cryptographically secure hash over the key (also called a fingerprint). Because the encryption over a zero block leaks information you should not use that to identify the encryption key.

You could actually use the AAD feature of GCM mode to calculate the authentication tag over the key identification data. Note that you cannot distinguish between compromise of the fingerprint and using an incorrect key. It's however less likely that the fingerprint is accidentally damaged than the entire structure of IV, AAD, ciphertext and authentication tag.

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

1) GCM is a streaming mode, so it needs no padding 2) Relying on padding for integrity checking is a really bad idea. It's very likely that you open yourself up to padding oracles that way. 3) GCM has an integrated MAC, that already takes care of any integrity checks you need.
– CodesInChaosSep 2 '12 at 10:36

The question is about recognising incorrect keys, not integrity checking. Using padding is fine for that specific problem. You are correct about GCM, my mistake.
– rossumSep 2 '12 at 12:07

A pretty rare lapse rossum, I'm sure I'm making more. Do you mind if I keep it in my collection of rare lapses? :)
– Maarten BodewesSep 2 '12 at 15:11