views:

136

answers:

5

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 of file some string (for example: "GOOD");
  • Encrypt file
  • When decrypting first decrypt the beginning of file and check for "GOOD" string

Is this correct?

+3  A: 

You might consider storing some hash function of the file at the beginning such as MD5.

falagar
+8  A: 

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!)

Pontus Gagge
zlib is a compression library.
Gumbo
@Gumbo: Right you are. Sloppy of me. Changed to SO question link.
Pontus Gagge
+4  A: 

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.

PeterK
zlib is a compression library.
Gumbo
I'll just add - the problem with having a fixed string encrypted at the start is that it's relatively easy to exploit that to crack the code. As an example, it's common enough to compress data (e.g. with zlib) for entropy reasons that make it harder to crack. But you don't use a standard zip tool for that compression because the header, even though not a completely fixed string, is still plenty to work with for cracking the code. Headerless compression must be used. Having a hash of an initial string is still a clue, but the longer the string you hash, the harder it is to exploit.
Steve314
+1  A: 

Having a known encrypted value will assist a cracker in figuring out your encryption key.

James Curran
True, so maybe put at beginng of file md5(password+salt)?
TA906
+1  A: 

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.

246tNt