Search code examples
phppasswordssalt-cryptographypbkdf2

PBKDF2 password storage - how to validate?


I am trying to figure out how to validate the password, during login, when using PBKDF2. I am using PHP, so here is a basic password generation code:

$salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
echo hash_pbkdf2('sha256', 'password', $salt, 1000, 32);

I have stored this hashed password in the database. I don't know how to test this password against a login input since I don't have the salt and the salt is generated randomly for each user. How can I "extract" the salt from the stored password, prepend it to the inputted password and test the result against the stored password?


Solution

  • You need to store the salt together with the hash, for example:

    $hash = $salt . '|' . hash_pbkdf2(.., .., $salt, ..);
    

    You can then later extract the salt from it again and feed it back into the validation algorithm. In fact, you should do this with all the relevant input parameters for the hash (except for the password itself, obviously), to allow you to change your algorithm later as needed while still being able to validate already hashed passwords:

    $hash = $algo . '|' . $salt . '|' . $rounds . '|' . hash_pbkdf2($algo, .., $salt, $rounds, ..);
    

    In fact, you should use the crypt API, which already does it like this.

    But really, you should be using password_hash, which is a user-friendly wrapper around crypt which ensures that you do it right.