0

我有以下 PHP 脚本来散列用户的密码,但是,当我尝试将散列变量与原始密码进行比较时,它返回 false。

$hash=hash("whirlpool","hello");

if("hello"===$hash){echo "TRUE";}
else{echo "FALSE";}

有谁知道我做错了什么或者我可以做些什么来改进这段代码以使其正常工作?我需要哈希与变量相同,所以我可以实际使用它。

旁注:我想使用大小合适的加密(这就是我使用“漩涡”算法的原因),所以我不想使用 md5、sha1 等...

提前致谢。

4

3 回答 3

2

您不应该将这些值比较为

if(hash('whirlpool', 'hello') === $hash) echo 'true';
else echo 'false';
于 2012-12-04T23:45:54.547 回答
1

散列函数是一种单向加密算法(单向意味着您无法从给定输出计算输入)。它需要一个输入并输出一个相当长的数字(通常以十六进制格式表示)。So when you apply a hash algorithm on a given input (in your case you apply the whirlpool algorithm on "hello") it returns a digest (in your case digest hex string would be 0a25f55d7308eca6b9567a7ed3bd1b46327f0f1ffdc804dd8bb5af40e88d78b88df0d002a89e2fdbd5876c523f1b67bc44e9f87047598e7548298ea1c81cfd73). 显然“你好”不等于“0a25f..”。使用哈希算法的一个常见场景是保护保存在数据库或其他某种身份存储中的密码。因此,在比较给定密码时(例如

因此,您不想将“hello”与先前生成的哈希进行比较,而是将“hello”的哈希与先前生成的哈希进行比较。

$hash = hash("whirlpool","hello");
if(hash("whirlpool","hello") === $hash){
    echo "true";
}

假设你想检查一个提交的密码,你可以这样写:

$pw_stored = "0a25f..." //(... left out some chars) that's the hash you got from the db
if(hash('whirpool', $_POST['password']) === $pw_stored){ // $_POST['password'] is the password a user has entered in a login form 
    echo "true";
}
于 2012-12-05T00:07:04.553 回答
1

比较哈希时,您可能还想对比较值进行哈希处理,例如

$hashed_password = hash("whirlpool", "hello");
$input = "hello";

if (hash("whirlpool", $input) === $hashed_password) {
    echo "TRUE";
} else {
    echo "FALSE";
}

PS:如果你真的想用漩涡,加个。此外,请遵循OWASP上的最佳实践。

于 2012-12-04T23:44:18.013 回答