我正在尝试使用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);
?>
现在,如果我例如使用'password'生成哈希值,那么我将得到一个哈希密码,它使用了随机生成的盐。接下来,如果我再次输入'password'并使用验证函数,我会得到true,这意味着密码匹配。如果我输入错误的密码,则会得到false。我的问题是这怎么可能?随机生成的盐又怎样都没有影响吗?
password_xxx()
函数,可以消除任何此类代码的需求。还有一个向后兼容的库可供下载,该库将这些PHP 5.5密码函数实现到5.3或5.4中。您可能想要尝试它;它会为您节省大量工作。请参见https://github.com/ircmaxell/password_compat - Spudley