0

I am trying to generate a random salt to be used in hashing a password. I am a bit new to password hashing, but form what I understand, when using BCrypt algorithm, you will get as a result a 60 characters long hashed string.

22 characters Out of these 60 characters should the salt value, which is prepended to the resulting hash.

I used a simple code to make sure that the randomly generated salt is the same one that is going to be prepended to the actual hash:

$salt = substr(strtr(base64_encode(openssl_random_pseudo_bytes(22)), '+', '.'), 0, 22);
echo "Salt Value is: ".$salt . "\n";

The output was: Salt Value is: XKFB8DHMiXaYTzRAHtRhX7

Then I encrypted a password using the same generated salt as follows:

$cost = 8; 
$EncryptedPassword = password_hash($Password, PASSWORD_BCRYPT, ['cost' => $cost,'salt' => $salt]);
echo "Encrypted Password: " . $EncryptedPassword . "\n";

The output was not what I expected:

Encrypted format: $2y$10$XKFB8DHMiXaYTzRAHtRhXutlLLG8XIZjj5XGeyoUZobEtnkOn/M/S Where the resulting salt is not exactly the one I used for hashing, i.e. that last character of the salt value is always different.

The randomly generated salt is: XKFB8DHMiXaYTzRAHtRhX7

The resulting salt value is: XKFB8DHMiXaYTzRAHtRhXu

My question is what could be the problem, and how could I get the same randomly generated salt value embedded in the password hashed string without getting it changed?

  • Why not use password_hash? http://php.net/manual/en/function.password-hash.php – Matt Jun 28 '17 at 17:33
  • 2
    You don't need to generate salt, `password_hash()` will do it for you. – Alex Howansky Jun 28 '17 at 17:35
  • Go with zaph 's answer that's the recommended way, but read this [explanation](https://stackoverflow.com/a/16280909/575765) if you are interested in the reasons of the truncated salt. – martinstoeckli Jun 29 '17 at 07:00

1 Answers1

1

It is simpler and more secure to just use password_hash() and the companion password_verify() for PHP.

Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier.

No salt needs to be supplied and is best not to supply one, in PHP 7.x the salt option has been removed.

Example: password_hash("aPassword", PASSWORD_BCRYPT)

zaph
  • 111,848
  • 21
  • 189
  • 228
  • Im trying to use the following code to make sure the same salt is being used in hashing: ` $cost, 'salt' => $salt]); echo nl2br("Encrypted Password: " . $EncryptedEnteredPassword . "\n"); ?>` The last salt character is different – Tofik al-Radi Jun 29 '17 at 12:06
  • The point is not to use the same salt, why do you want to use the same salt? – zaph Jun 29 '17 at 12:09
  • I am not using it, I just echoed it so I could verify what is going on. I just need to know why I am getting a different salt's last character – Tofik al-Radi Jun 29 '17 at 12:31