php - password_verify 和 doveadm pw -t 如何在不加盐的情况下验证密码

标签 php hash salt verify

我目前正在尝试理解哈希和盐。据我了解,如果我只有密码和生成的哈希值(这是用随机盐生成的),就不可能验证密码。 如果我不加盐,PHP 中的password_verify 函数如何验证我的密码?后台是否有一个隐藏变量,为 php 哈希函数存储它?

如果是这样的话,怎么可能

doveadm pw -t '{SHA512-CRYPT}$6$myhash...' -p "qwertz"

也要验证它,即使我在完全不同的计算机上运行它?那是 Dovecot(一种 MDA)附带的工具。

这是我的 PHP 代码,它创建一个包含 64 个字符的随机盐,将其与密码组合,创建哈希并通过 password_verify() 验证哈希。

我今天才开始研究整个hash/salt/pepper,所以我的整个思路可能存在巨大缺陷。

<?php
$password = "qwertz";
$salt = createSalt(64);
$hash = crypt($password, "$6$$salt");

if (password_verify($password, $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}


function createSalt($length){
    $chars = "IrhsYyLofUKj4caz0FDBCe2W9NRunTgQvp7qOXmS5GM3EJV6i8tAHdkPbxwl1Z";
    $salt="";
    for($i=0; $i < $length; $i++){
        $newchar = substr($chars, rand(0,strlen($chars)-1),1);
        $salt .= $newchar;
    }
    return $salt;
}
?>

最佳答案

散列包含几条信息。这article解释了 Unix 使用的格式,但我相信 PHP 密码函数使用类似的格式(如果不相同的话):

The hash field itself is comprised of three different fields. They are separated by '$' and represent:

  • Some characters which represents the cryptographic hashing mechanism used to generate the actual hash
  • A randomly generated salt to safeguard against rainbow table attacks
  • The hash which results from joining the users password with the stored salt and running it through the hashing mechanism specified in the first field

它还可以包括用于生成哈希的每个算法的确切选项,例如算法成本:

var_dump(password_hash('foo', PASSWORD_BCRYPT, [
    'cost' => 8,
]));
string(60) "$2y$08$7Z5bTz7xXnom8QsrbZ7uQetMLxOZ7WjuDkUYRIh73Ffa17GV1Tb7q"

此处$2y$08$表示使用了成本为8的Bcrypt。

如果我们使用 PHP/7.2 中可用的更新的 Argon2,则参数会更多:

$argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0

关于php - password_verify 和 doveadm pw -t 如何在不加盐的情况下验证密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48232449/

相关文章:

PHP:多维数组上的 array_push 并显示其元素

php - 如何创建一个查询来获取使用 where 子句作为结果数组索引的结果?

c++ - 在c++中实现hashmap的过程中发生了奇怪的事情

c# - 当为密码创建哈希+盐时,有没有办法避免将盐保存为数据库中的单独字段

php - 使用PHP的GDlib imagecopyresampled时可以保留PNG图像透明度吗?

php - 从地址字段中拆分门牌号

ruby - 使用嵌套散列和散列作为默认值未按预期工作

perl - Perl 中的哈希和智能匹配运算符

PHP - 发送用于散列的密码盐

php - PHP 和 MySQL 中的加盐