让我们用以下内容哈希并加密密码:
<?php
$hash = password_hash('bonjour', PASSWORD_BCRYPT, ['cost' => 12, ]);
// no salt option mentionned
// then salt will be generated randomly, see password_hash documentation
echo $hash;
?>
每次重新加载页面时结果都会发生变化,这是正常的:盐是随机生成的,可以是:
$2y$12$FlxBBjTjelKkGY.SJarlL.THUZBwcl7M6V35DmZmTmYJZRwhpRkIW
$2y$12$p2pkD116hBHNc/2nyQ2WyOkrn.h8xvWvM1.Lmvsnhms2Y6zsb.j1e
$2y$12$u4ipdQQM926jfanpXnwtkupv2CH/uWoPvK563tG7p.z35GcOBOZdS
etc.
在上一段代码中,盐似乎存储在无处(我错了吗?)。但最后password_verify
能够使用哈希检查密码,
并且它适用于所有结果,无论盐是什么。
<?php
echo password_verify('bonjour', '$2y$12$FlxBBjTjelKkGY.SJarlL.THUZBwcl7M6V35DmZmTmYJZRwhpRkIW') ? 'yes' : 'no';
// yes
echo password_verify('bonjour', '$2y$12$p2pkD116hBHNc/2nyQ2WyOkrn.h8xvWvM1.Lmvsnhms2Y6zsb.j1e') ? 'yes' : 'no';
// yes
?>
password_verify
无需在某处存储salt
即可查看密码是否正常?
答案 0 :(得分:1)
来自PHP.net手册
Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.
salt基本上用哈希编码。