Normally if I have a password, I would use this pseudocode:
$password = "this is the user's password";
/***/
$salt = GenerateSalt();
$hash = Hash($password);
$hash = Hash($hash . $salt);
However, as I understand it, PHP has a crypt() function which takes a salt as well as the number of iterations of a particular algorithm. Apparently you are.. supposed to pass the returned hash of crypt back into crypt as the salt. I do not understand this.
Can anyone please clarify how crypt works? Do I still need to append my own salt and rehash? In that case, would I just use a fixed salt for crypt, and then generate a separate crypt for each user? Or does crypt’s $salt parameter take care of that for me?
The output of
cryptconsists of:When you pass this output als “salt” back to
crypt, it will extract the right algorithm and salt, and use these for the operation. If there is only an algorithm mentioned, it uses this one and generate random salt. Otherwise it will choose a default algorithm and generate random salt. Thehashpart in the passed salt parameter is ignored.So you can simply compare your stored_hash with crypt(password, stored_hash) – if it is equal, it quite likely was the right password.
Here is an pseudocode explanation (in PHP-like syntax) how crypt works:
The individual crypt_xxx functions then do the real work, depending on the algorithm.
(Actually, the generation of random salt is missing in this description. It will be done if the $real_salt is empty.)