Check password before decryption
I'm writing small program (C++) to encrypt/decrypt files. Before decryption I would like to check if password given by user is correct. My idea:
- Add at the beginning 开发者_如何学Pythonof file some string (for example: "GOOD");
- Encrypt file
- When decrypting first decrypt the beginning of file and check for "GOOD" string
Is this correct?
The primary advice on encryption: Don't implement it yourself. There's plenty of excellent libraries out there.
What you're suggesting provides a backdoor (crib) for breaking your encryption. Even experts get things wrong when designing crypto (not to mention key management!).
(Not, of course, that I'm suggesting Bruce would ever get things wrong!)
Instead of a "good" string, i would suggest using a checksum of some sort, for example MD5, CRC, SHA256 etc. This checksum will be calculated from the first few bytes (for example 128) of the file.
Anyway, using a existing encryption library is a much better idea.
You might consider storing some hash function of the file at the beginning such as MD5.
Having a known encrypted value will assist a cracker in figuring out your encryption key.
Better yet: Use the hash (SHA256 for eg) to cipher the file itself (using AES256 for eg), and append a hash of the clear-text file (can be anything, even simple CRC) to the ciphered file.
To decipher:
- Ask password to user
- Hash the password with SHA256
- Decipher the file using the password hash as key
- Compute the CRC of the deciphered file
- If the computed CRC matches what was appended after the cipher text, the password was correct. If they don't match, the key wasn't good and you deciphered garbage which means the password was not good.
As a bonus, no need to keep a 'secret' key somewhere, it's all self contained. Plus bruteforce/dictionary attack are painful because you have to decipher the whole file for each try to check the CRC.
精彩评论