When encrypting data, I want to verify that the correct key was entered without hashing it. Is it safe to decrypt the ciphertext and compare the hash of it with the stored one or can the plaintext (which could be very long) be read from the hash?
2 Answers
As others indicated, this would not be a scheme that would conform to best practice. Considering that you are asking this question I would strongly suggest to use your code for practice only.
In principle you can hash data and then encrypt it. As the hash remains confidential until the key is found, this is considered when it comes to protecting the hash and the plaintext message. However, please note that hash-then-encrypt itself may not be secure; we generally prefer methods such as encrypt-then-MAC. Personally I would try and use a Password Based Key Derivation Function and an authenticated mode of encryption such as EAX / encrypt-then-HMAC (also taking care of the IV).
It is also a good idea to store some key check value (e.g. a MAC over some known data) next to it. That way you don't have the problem that you need to try and decrypt all of your database before you can check if your password is correct. Note that an adversary can validate if the master password is correct by simply decrypting a few blocks of data, so this won't give much if any advantage to a would-be attacker, while adding to the user experience.
- 96,351
- 14
- 169
- 323
A long plaintext doesn't mean it can not be guessed. If the hash of the plaintext is available to an attacker such an attacker can efficently verify any guess he may have as to the plain text.
In many real world scenarios we encrypt plain text with limited entropy, the text may be large but still have little information not known to the attacker. And with a simple efficient hash, even trying millions of guesses for the plaintext can be very practical.
There are better ways of authenticating encryption. We can do encrypt then mac, we can use combined methods like GCM. Both are better than a plain text hash.
- 12,053
- 1
- 24
- 55