PHP mcrypt_decrypt - 我可以确定是否使用正确的密钥解密数据?

I'm working on a php script and are using mcrypt to encrypt/decrypt arbitrary data.

When I decrypt encrypted data, using another key (e.g. I typed in the wrong password), the output won't be correctly decrypted of course.

If the wrong key has been used I would like to display an error message, but I'm thinking it's quite hard to validate the output string as correct "plaintext" (since the chars in the encoded data are also valid as input data).

Is there any way to get around this?


As I was writing this question, I got an idea :)

Could I possibly prefix the input data with a static "control" string and use this for validation when I decrypt?

I usually do this:

  • Hash the input data (file or message or whatever).
  • Encrypt the data.
  • Prepend the encrypted data with the IV and the hash of the data.
  • Send or store the IV + hash + ciphertext.

As the IV and hash are always the same length, there is no need to add padding or control characters.

On the receiving or reading side:

  • Extract the IV.
  • Extract the hash.
  • Extract and decrypt the encrypted text.
  • Hash the decrypted data and check if it does match the extracted hash.

So, you store the hash of the source data, NOT the hash of the key. As a commenter posted above, giving away the hash of your key is a vulnerability, as the attacker now needs only to search it in a rainbow table (it would compromise your data in a matter of seconds).

You idea of storing a control string is good too (certainly is faster) but it cannot allow you to confirm the message or data is indeed uncorrupted, only that the correct key was used.

The best way to add integrity to you encrypted data is to add MAC created ONLY on encrypted data.

Don't apply MAC on plain text, because MAC can reveal some information about that text. MAC is not created to provide security - only integrity.

So, right algorithm would be ENCRYPT-THEN-MAC!

More detailed information is available in this video http://d396qusza40orc.cloudfront.net/crypto/recoded_videos%2F7.4%20%5B974a4c90%5D%20.mp4