1

SO.

I want to use BCrypt for my user authentication form. I can register a user using the code

<?php
$salt = '$2a$07$R.gJb2U2N.FmZ4hPp1y2CN$';
crypt("secretpassword", $salt);
?>

Here instead of using a constant salt. I want to generate random salts using

// Posted Code from http://pastebin.com/wLxDEhD7.
$Allowed_Chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./';
$Chars_Len = 63;
$salt = "";
for($i=0;$i<45 ;$i++)
{
    $salt .= $Allowed_Chars[mt_rand(0,$Chars_Len)];
}

And store it into the database. Until this I am clear(I Hope :D) Next what I need is to check the password when the user logs in. For that I need the user's input data, the salt used for that user.

crypt("secretpassword", $salt);

I can get the user input, but how will I know the salt that has been used? I am not clear on this.

Codes have been copied from phpmaster.com and http://pastebin.com/wLxDEhD7 (from a question asked on SO, I am unable to find the question again) This is being used purely for educational purposes.

  • http://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php – Jon Hulka Jan 16 '13 at 06:58
  • umm, am not getting it correctly, please bear with me. am i supposed to store the hash in database? idk, is that a good idea? –  Jan 16 '13 at 07:00
  • What [Kitsune](http://stackoverflow.com/questions/14352849/using-bcrypt-and-generating-salts#comment19954360_14352900) said :) – Jon Hulka Jan 16 '13 at 22:10

1 Answers1

2

The salt is stored within the hash generated by BCrypt. So just doing this will work:

$passwordIsOk = crypt($password, $hash) === $hash;
laurent
  • 88,262
  • 77
  • 290
  • 428
  • Thanks, So u mean that while verifying the password of the user when they login, I do not need the salt used? I can simply use if(crypt($userpass,$hash) === $hash; ? what is data stored in $hash ? –  Jan 16 '13 at 07:01
  • Right, you do not need to store the salt since it's going to be embedded inside the hash by BCrypt. – laurent Jan 16 '13 at 07:02
  • what does the $hash store? –  Jan 16 '13 at 07:04
  • 4
    @SworoopMahapatra `$hash` is the previous output of a `crypt()` command. It's a formatted string that includes the algorithm used, the salt, and the hash. The `crypt()` command accepts it as an argument, and will take the salt from it and apply it to the first parameter as a salt. Salting is intended to prevent hackers from being able to leverage pre-computed hash databases to easily crack the passwords, along with ensuring that all stored passwords have a unique hash (because some users will have the same password, which without the salt would mean they'd have the same hash). – Kitsune Jan 16 '13 at 07:09
  • Thanks Kitsune. Thanks Laurent. :) All Cleared Up –  Jan 16 '13 at 07:11