所以我在试验bcrypt。我有一个类(如下所示,我从http://www.firedartstudios.com/articles/read/php-security-how-to-safely-store-your-passwords获得),其中有 3 个功能。第一个是生成随机 Salt,第二个是使用第一个生成的 Salt 生成散列,最后一个是通过将提供的密码与散列密码进行比较来验证提供的密码。
<?php
/* Bcrypt Example */
class bcrypt {
private $rounds;
public function __construct($rounds = 12) {
if(CRYPT_BLOWFISH != 1) {
throw new Exception("Bcrypt is not supported on this server, please see the following to learn more: http://php.net/crypt");
}
$this->rounds = $rounds;
}
/* Gen Salt */
public function genSalt() {
/* openssl_random_pseudo_bytes(16) Fallback */
$seed = '';
for($i = 0; $i < 16; $i++) {
$seed .= chr(mt_rand(0, 255));
}
/* GenSalt */
$salt = substr(strtr(base64_encode($seed), '+', '.'), 0, 22);
/* Return */
return $salt;
}
/* Gen Hash */
public function genHash($password) {
/* Explain '$2y$' . $this->rounds . '$' */
/* 2a selects bcrypt algorithm */
/* $this->rounds is the workload factor */
/* GenHash */
$hash = crypt($password, '$2y$' . $this->rounds . '$' . $this->genSalt());
/* Return */
return $hash;
}
/* Verify Password */
public function verify($password, $existingHash) {
/* Hash new password with old hash */
$hash = crypt($password, $existingHash);
/* Do Hashs match? */
if($hash === $existingHash) {
return true;
} else {
return false;
}
}
}
/* Next the Usage */
/* Start Instance */
$bcrypt = new bcrypt(12);
/* Two create a Hash you do */
echo 'Bcrypt Password: ' . $bcrypt->genHash('password');
/* Two verify a hash you do */
$HashFromDB = $bcrypt->genHash('password'); /* This is an example you would draw the hash from your db */
echo 'Verify Password: ' . $bcrypt->verify('password', $HashFromDB);
?>
现在,例如,如果我使用“密码”生成哈希,我会得到一个哈希密码,该密码采用随机生成的 Salt。接下来,如果我再次输入“密码”并使用验证功能,我会得到密码匹配的真实含义。如果我输入错误的密码,我会得到错误的。我的问题是这怎么可能?那么随机生成的 Salt 呢?怎么一点效果都没有?