5

我在使用 crypt() 时遇到问题,如果用户有密码(在此示例中为密码 1),并且他们将其更改为密码 2,则散列返回相同的结果。你可以在这里测试一下:OLD LINK 输入密码1作为当前密码,密码2作为新密码并确认密码,你会看到结果。如果输入完全不相似的密码,则没有问题。我知道还有其他方法可以散列密码等。我比什么都好奇。我的代码如下:

<?php

$oldpassword="password1";

echo "<form method=\"post\">
<p>Enter Current Password: <input type=\"password\" name=\"currentpassword\" /></p>
<p>Enter New Password: <input type=\"password\" name=\"password\" /></p>
<p>Confirm New Password: <input type=\"password\" name=\"confirmpassword\" /></p>
<p><input type=\"submit\" value=\"Change Password\"></p>
</form>";

$user_id = $_SESSION['user_id'];
$pass=$_POST['password'];
$salt = 'xxxxx';
$currentpassword = crypt($_POST['currentpassword'], $salt);
$oldpassword = crypt($oldpassword, $salt);
if(isset($_POST['password'])) {
    if ($currentpassword !== $oldpassword) {
        echo "The password you entered for current password does not match our records.";
    }
    else {
        if ($_POST['password'] && $_POST['confirmpassword']) {
            if ($_POST['password'] == $_POST['confirmpassword']) {
            $hash = crypt($pass, $salt);
                if ($hash == $currentpassword) {
                    echo "Current Password:&nbsp;";
                    var_dump($_POST['currentpassword']);
                    echo "<br/>";
                    echo "New Password:&nbsp;";
                    var_dump($_POST['password']);
                    echo "<br/>";
                    echo "New Hash:&nbsp";
                    var_dump($hash);
                    echo "<br/>";
                    echo "Current Password Hash:&nbsp";
                    var_dump($currentpassword);
                    echo "<br/>";
                    echo "<hr/>";
                    echo "Your new password cannot be the same as your current password.";
                }
                else {
                    echo "Your password has been changed successfully<br/>";
                }
            } else {
                echo "Your passwords do not match. Please try again.";
            }
        }
    }
}

?>
4

1 回答 1

13

要使用crypt,您必须提供适当的盐。每个算法都有自己的盐格式。我的猜测是您使用的随机字符很少作为盐,这与任何高级算法都不匹配,因此 php 将您的盐减少到前 2 个字符并回退到基本DES算法。DES算法哈希最多 8 个字符,并且两者password1都是password29 个字符长,因此只能password从两者中使用,因此哈希值相同。

解决方案:为最强的可用算法使用适当的盐格式,为每个密码生成随机盐

推荐的解决方案:https ://github.com/ircmaxell/password_compat (用于 php 5.3.7 - 5.4.x)并在切换到 php 5.5 后:http: //php.net/password_hash

于 2013-02-22T23:28:59.877 回答