0
votes

So I'm in the process of learning PHP and am working on a login page. I already figured out how to register a new user using a SHA256 to hash $salt+$password. I know there are slower encryption methods like bcrypt but for learning purposes I'm just using SHA256. My question is, after using this to encrypt:

function HashPassword($password) {
  $salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); 
  $hash = hash("sha256", $salt . $password); column
  $final = $salt . $hash;
  return $final;
}

using prepared statements, what is the best way to retrieve the hash password from the database so I can validate it using a function like this?

function ValidatePassword($password, $hash_pass) {

  $salt = substr($hash_pass, 0, 64); 
  $trueHash = substr($hash_pass, 64, 64); 
  $reHash = hash("sha256" , $salt . $password); 

  return $reHash == $trueHash;
}
2

2 Answers

5
votes

The principle is that you cant retrieve the password; instead, you use the same HashPassword function to calculate a hash of the password attempt and then query the database for matching records.


EDIT

Looking again at your HashPassword function, I realise that you don't want to generate the random salt therein, but rather take $salt as an argument; you will either pass in the value from your existing database record, or pass in a randomly generated one, as appropriate.

1
votes

You basically save the password hashed with a salt to make it not recognizable.

In case your database gets hacked at some point, the hacker can't read the password directly. Instead he will have to recreate the hashed value.

If you don't use a different (random) salt for each user, the hacker will only have to create one table with all possible hash values and compare that to your saved hashed passwords.

If each password, however, has a different salt added to the password, before hashing, the hacker has to create a new table for each single password, thus increasing the effort needed to get the real passwords a lot. One hopes that this will make in inefficient or too costly for the hacker.

For you as a coder that wants to validate login credentials you have to follow the following pattern:

  1. Get the salt saved in the database.
  2. Compute the has value of the concatenated hash = salt + password
  3. Compare the computed has with the saved one hash === savedHash
  4. If they are the same, it was the valid password. If not, it was a wrong password.