1

I am trying to figure out the correct use of password_hash I have the following script below

<?php
  $password = "test3";
  $hashAndSalt = password_hash($password, PASSWORD_BCRYPT);

  echo $hashAndSalt;
?>

as far as I know this is supposed to create a salt too?

When ever I run the script the beginning of the hash starts with "$2y$10$" the remainder always changes on each run.

$2y$10$.YHHLeFYcQoE6c//vl587uIFTOljmpmuDnSA0w0dxo1Rrpvi5zM9m   <- run one
$2y$10$b6n3chpTQk1X7c0OdPp0ceZmw3GvZFsLx9FHq9RnYaJgbld915oYG   <- run two
$2y$10$AGffB7R1rTko8UmS1m6wT.ybG78.CkwrxqoRteNMeRPXexpSJW5iO   <- run three

Is it supposed to work like this? is this the correct way of storing password in database?

Arya
  • 8,473
  • 27
  • 105
  • 175
  • the hash becomes part of the crypted string. can't remember exactly where the spit is, but if `h` is the hash, and `c` is the crypted pw, then your strings are a correct `$2y$10$hhhhhhhccccccc`-type format. – Marc B Jul 21 '14 at 22:39
  • In addition to Marc's comment above, the `2y` between the first two `$` signs identifies the algorithm used, while the `10` between the second two `$` signs is the `cost` factor – Mark Baker Jul 21 '14 at 22:47

1 Answers1

3
$2y$10$.YHHLeFYcQoE6c//vl587uIFTOljmpmuDnSA0w0dxo1Rrpvi5zM9m
|  |  |                    |                               |
|  |  |                    |                               |
|  |  |                    |---------------------------------Hashed Password
|  |  |----------------------Salt
|  |----Cost
----Algorithm

The hash contains all the information necessary to see if the password matches the hash for a given string. You know the algorithm it was hashed with, the salt, and what it hashed to. So all you have to do is supply a string, pass it through the same algorithm with the same salt and cost, and it will either equal the hash or not.

So to answer your question, yes it is supposed to work like that. The salt changes every time, which means the hashed password changes every time, but you can always check if a password hashes to the same hashed password, because the hash contains the salt.

dave
  • 62,300
  • 5
  • 72
  • 93
  • Refer to [this](http://stackoverflow.com/questions/6832445/how-can-bcrypt-have-built-in-salts) for more Bcrypt info. – Mark Fox Jul 21 '14 at 23:48