7

这是crypt() 的 PHP 手册页中的示例:

<?php
$password = crypt('mypassword'); // let the salt be automatically generated

/* You should pass the entire results of crypt() as the salt for comparing a
   password, to avoid problems when different hashing algorithms are used. (As
   it says above, standard DES-based password hashing uses a 2-character salt,
   but MD5-based hashing uses 12.) */
if (crypt($user_input, $password) == $password) {
   echo "Password verified!";
}
?>

为什么这行得通?我认为这'mypassword'是我希望实际管理员使用的密码。所以我先将其加密,并将其设置为$password. 显然,我必须将其存储在数据库中。但在接下来的几行中,它被用作盐和我正在比较的东西,我不明白怎么可能crypt($user_input, $password)等于到. 如果最后一行是$password$user_input$password$password

if (crypt($user_input) == $password) {
   echo "Password verified!";
}

我不明白什么?

4

1 回答 1

8

crypt是一个单向函数并返回一个已经包含盐的字符串。输出类似于存储在/etc/shadow.

来自php.net的示例:

<?php
echo 'result: ' . crypt('somepassword');
echo 'result: ' . crypt('somepassword');
echo 'result: ' . crypt('somepassword');
?>

result: $1$K2D8DGwq$b05uO37aMwO4rnDlB9Rsi1
result: $1$aPBvu2y.$213YVEs8/5m.jMCXSScly/
result: $1$dW3Xu2p6$nuCtJe2zzlgBMLxN2oZCx/

当将用户输入与 crypt 结果进行比较时,该函数会自动从字符串中提取盐。

于 2010-02-10T09:46:42.463 回答