6

I have a program which uses AES-256 in CBC mode to encrypt and decrypt files. As I have quickly realized, AES will even use an incorrect passphrase to decrypt data, which leaves me with no way to validate whether the passphrase was correct or not and, in turn, whether I'm decrypting things successfully.

One idea which was suggested before was to embed a known value in beginning of the encrypted data to validate whether decryption produced an expected result. Essentially, since the IV is a known value, I thought of simply hashing it and embedding it as the first 32 bytes in the file. If, after the first block is decrypted, the first 32 bytes equal the hash of the IV, we can know that decryption succeeded. If not, we can know that it failed.

Does this in any way compromise my encrypted files?

Naftuli Kay
  • 1,007
  • 1
  • 11
  • 14

3 Answers3

3

That would work and almost certainly wouldn't have any negative impact on security, but it would be cleaner just to have a string of 16 0x00 bytes at the start of a message, instead. Not only does this save you the trouble of hashing, but you stay within the standard threat model for CBC which assumes the IV is independent of the message blocks. (One can come up with pathological yet technically still secure hash functions that would cause your approach to become insecure.)

And a quick note: the block size is 16 bytes, not 32 bytes. The 256 in AES-256 refers to the length of the key, not the block.

You should look into using a message authentication code, such as HMAC. Doing so will not only validate a correct passphrase, but will also ensure the ciphertext has not been tampered with. (CBC will prevent someone from learning information about the plaintext, but will not stop someone who already knows it from tampering with the ciphertext so that parts of it decrypt to strings of his choosing.)

Edit: A couple warnings, if you decide to go with a MAC (and I think you should): (1) Use different keys for CBC and the MAC; (2) MAC the ciphertext, not the plaintext; (3) Concatenate the IV to the ciphertext before using the MAC.

Seth
  • 4,488
  • 24
  • 28
3

If you use an authenticated encryption mode (which you should be doing anyway) like GCM or EAX, this is a built-in feature.

Otherwise, use an HMAC.

Stephen Touset
  • 11,162
  • 1
  • 39
  • 53
0

With AES-256-CBC, if something is known about the padding used, then it may be possible to determine whether or not a key provided is correct for decrypting a given ciphertext, by focusing on the last block of ciphertext (without using an HMAC or magic value). See How do I detect a failed AES-256 decryption programmatically? for a working example.

mti2935
  • 969
  • 8
  • 10