Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

php - Laravel 4.1 Hash::make inconsistency

I was trying to match hashed password from the database against password - hashed from the login form and it doesn't match no matter what.

Then I've done some consistency tests.

$password = Hash::make('secret');
echo $password;

I've been getting different results each time I refresh the page. Not like md5, it's consistent.

Am I missing something?

Or am I using/doing it wrong?

Why Hash::make produces inconsistent result with the same args?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's correct, and that's by design.

AFAIK, the function uses the password_hash() php function, and defaults to the PASSWORD_BCRYPT flag, which

PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the "$2y$" identifier. The result will always be a 60 character string, or FALSE on failure.

That means a salt is automatically generated at each call, and inserted within the generated string, which contains: an identifier for the algo (in this case, $2y$), the iteration cost (defaults to 12), the hashed password, and the generated random salt.

That means, thus, everytime you hash your password a new salt is created, therefore the string will always be different - even if the password is the same. That's one of the strengths over a simple md5 hash without salt.

To check it, you use Hash::check(), which uses the password_verify() php function, which analyses the hash, guess the algo used, takes, the embedded salt, and can therefore check if the procedure, given the same starting conditions, creates an identical hash.

Edit

Indeed, this is the method (in Illuminate/Hashing/BcryptHasher)

 * Hash the given value.
 *
 * @param  string  $value
 * @param  array   $options
 * @return string
 */
public function make($value, array $options = array())
{
    $cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;

    $hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));

    if ($hash === false)
    {
        throw new RuntimeException("Bcrypt hashing not supported.");
    }

    return $hash;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...