4

I'm Encrypting the data using AES-128 bit Encryption. I need to check whether the key is correct at the receiver side. How can I do that?

Suppose At the receiver The user is asked to enter the KEY for decrypting. As far as I know giving a wrong key generates some gibberish data. How can I prevent that and report back to user that the key provided is incorrect?

E.J
  • 135
  • 1
  • 2
  • 7

3 Answers3

4

Use AES 128 in GCM mode. This will generate a tag during encryption. Send that tag along with the ciphertext to receiver. If the receiver decrypts it with the wrong AES key, the sent tag and receiver computed tag will differ. Alert your user that the AES key is incorrect OR that the encrypted data is corrupted.

DeepSpace101
  • 1,717
  • 3
  • 17
  • 24
1

You can indeed use authenticated mode as DeepSpace101 suggested, but it has the disadvantage that if the data is large and the last part is e.g. missing that you may not see the difference between missing data and a wrong key being entered. It also slows down the verification as you need to verify all the data before the key can be compared (and no, this will not deter an attacker).

Another method is to use a KCV, most of time a block encrypt of zeros. This has the disadvantage that you don't want to use another block encrypt of zeros; so it is too dangerous in my opinion. You could also use a hash over the key as KCV, but that shows another issue (already present with the previous flawed try): if you reuse the key then the hash will be the same.

So all those things are sub-optimal at best. I'll suggest another one: use a KBKDF such as HKDF and provide a salt and a derived key value with the ciphertext. Use the salt and the input key as input of the KBKDF and calculate the derived value. Then compare it with the derived value stored with the ciphertext. Note that KDF's are irreversible so this should not give an attacker any advantage (but note that the key value is required in memory to do this).

Note that if you want to protect against active attackers you would need to include the salt & hash in the authenticated data (AAD data for authenticated / AEAD ciphers). Of course an active attacker may still let you believe that your data is at fault instead of the key if the key is reused by supplanting a previous salt/derived value - that cannot be avoided.

Maarten Bodewes
  • 96,351
  • 14
  • 169
  • 323
0

You would do that by checking the integrity of the data decrypted. A simple way to do that is to add a magic value at the beginning of your data, and check if this magic value is effectively present when decrypting.

This magic value can for instance either be a constant, or a random value & the result of an operation on it (a hash function, or even just a binary NOT, etc.).

Dillinur
  • 407
  • 3
  • 6