yii CPasswordHelper: hashPassword and verifyPassword

CPasswordHelper works like PHP’s functions password_hash() and password_verify(), they are wrappers around the crypt() function. When you generate a BCrypt hash, you will get a string of 60 characters, containing the salt.

// Hash a new password for storing in the database.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

The variable $hashToStoreInDb will now contain a hash-value like this:

$2y$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |                     |
 |  |  |                     hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |
 |  |  salt = nOUIs5kJ7naTuTFkBy1veu
 |  |
 |  cost-factor = 10 = 2^10 iterations
 |
 hash-algorithm = 2y = BCrypt

The salt you can find after the third $, it is generated automatically by password_hash() using the random source of the operating system. Because the salt is included in the resulting string, the function password_verify(), or actually the wrapped crypt function, can extract it from there, and can calculate a hash with the same salt (and the same cost factor). Those two hashes are then comparable.

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);

Leave a Comment