C++ – A question about storing passwords

cpasswords

I'm creating a program (in C++) that will password protects its user's database (.dat) file. I'm confused on where to store the password? In the user's database file or somewhere else.

I'm new to this concept. I don't know where a program should store the hashed password. I've been thinking for this from a long time.

I have a question too. If a program stores hashed password in the database file (along with users data) is it possible for an attacker to modify the hash inside the file to some common hash like the hash of the text 'password' so that the password becomes 'password'?

Edit: Okay! I've somewhat understood the password storing concept. This is what I've understood:

Get the password from the user

Hash it (I will use SHA-512)

Store the hash in the database file

Done

Probably, I didn't understand the symmetric hash concept. Please explain me in an easy way. And the question I have is… I'll better explain it with an example.

Assume this is user's file's content

thisismydatabasefile

User decides to add a password. He types in the password and we hash it. The generated hash is somerandomhash. We encrypt the file with somerandomhash as the password and the hash is included in the encrypted file. So now the file content is

encryptedfilesomerandomhash

Imagine the attacker got the encrypted database file. He knows that the hash of the password is "somerandomhash". He now modifies the password hash 'somerandomhash' to something common like 'somehashthatheknows'. So what is a better way to store a password.

For ease, how do programs like zip, 7z, rar etc store passwords inside a archive file?

Best Answer

You correctly identified that storing the hash anywhere on the disk makes the password vulnerable to attacks such as breaching file access control, known cypher-text attacks, or chosen cypher-text attacks.

Security Solution: Do not store a hashed password on the disk.

Since your database is just a file we can use the general way to securely password protect a file on disk.


Algorithm To Securely Password Protect A File:

  1. Have the user input a password at runtime for the file. (database in your case)
  2. Hash the password. (I'd use SHA-256)
  3. Use the hash to derive a symmetric 256-bit key. (I'd use hash directly as the key)
  4. Use the 256-bit key to encrypt/decrypt the database file on the disk. (I'd use the AES algorithm)

Major Pro: Database encryption key is generated at run-time and never stored on the disk.

Minor Con: Encryption and key derivation becomes implementation specific and laborous to implement.

You get to decide whether the required security for the application is worth the time to implement the security protocols correctly.