password_hash function in php 5.5

与世无争的帅哥 提交于 2019-12-11 03:48:55

问题


i have the following function that hashes a password and stores it in a database. i am trying to use the password_hash function in php 5.5 but its giving me weird results.

function hashpass($password)
{
    include("includes/config.php");

    $password = password_hash($password, PASSWORD_DEFAULT);
    return $password;
}

I then output the result for the same static password which i am just testing as "testpassword" and it keeps giving me different hashes. Why is that? if it keeps doing that i will never be able to verify the password because it will never yield the same hash for the exact same string.

Is there something that i need to configure or set before hand for this to work correctly?


回答1:


When you hash a password with password_hash, a random salt is being generated, used in the hashing process and prepended to the result. This is precisely for the purpose of avoiding the same passwords resulting in the same hash every single time; to avoid easy generation of rainbow tables. (All terms you should probably google. :))

To verify a hash generated with password_hash you need to use password_verify, which uses the salt embedded in the hash to reproduce and compare the hash from another plaintext password.




回答2:


Hashes generated by password_hash (and most good password hashing algorithms) are salted. That means that an extra set of random data is added to each password before and sometimes during hashing.

A common format for password hashes is ##xxxxxxOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO, where:

  • ## is the hashing algorithm identifier,
  • xxxxxx is the salt, and
  • OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO is the hashed password.

When comparing the stored hash with a given clear-text password, the algorithm will take the ##xxxxxx part of the hash and use it to calculate a new password hash (say ##xxxxxxNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN). It them compares the two hashes, and if they are equal, it can assume that the given clear-text password was the same as the initial password.

Because this differs from static hashes, you must use password_hash to initially hash the password on registration or password change, and password_verify to check if the given password is correct.



来源:https://stackoverflow.com/questions/25207875/password-hash-function-in-php-5-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!