// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// 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);
1 回答
PHP的文档对表达式"salt"有点误导,实际上
crypt()
函数需要哈希参数,而salt只是这个参数的一部分 .好处是,所有参数都将包含在生成的60个字符的哈希字符串中,因此您不需要单独存储它们,只需存储字符串即可 . 成本因子提高到2的幂,这意味着,将成本因子增加1,将使计算时间加倍 .
PHP现在有一个函数password_hash(),可以为您处理所有困难的部分 . 使用此函数而不是crypt,它将生成一个安全的随机盐 .
我写了一个关于这个主题的教程,如果你有兴趣看看here .