PHP :从哈希解密密码


PHP : Decrypt password from hash

因此,我使用以下代码成功地将密码加密为密码哈希:

class PassHash 
{
    // blowfish
    private static $algo = '$2a';
    // cost parameter
    private static $cost = '$10';
    // mainly for internal use
    public static function unique_salt() 
    {
        return substr(sha1(mt_rand()), 0, 22);
    }
    // this will be used to generate a hash
    public static function hash($password) 
    {
        return crypt($password, self::$algo .
                self::$cost .
                '$' . self::unique_salt());
    }
    // this will be used to compare a password against a hash
    public static function check_password($hash, $password) 
    {
        $full_salt = substr($hash, 0, 29);
        $new_hash = crypt($password, $full_salt);
        return ($hash == $new_hash);
    }
}

这就是我加密密码的方式:

 $password_hash = PassHash::hash($user->getPasswordHash());

但是当我尝试以正常模式显示密码时,我现在遇到了一个小问题。

从该哈希中解密密码的最佳方法是什么?

您无法解密哈希(好吧...从技术上讲,你可以,但你不应该)这就是哈希的用途(不解密)。您需要使用与存储哈希相同的哈希算法对收到的密码进行加密(哈希),并将哈希值相互比较。

$password_hash = PassHash::hash($user->getPasswordHash());
if($stored_password === $password_hash){
    //The passwords are the same
}

总而言之,您不想让任何人(甚至您自己)知道用户的密码是什么(或与此相关的哈希值)。用户会知道,因为他输入并记住了它(希望无论如何)。没有其他人与查看用户的密码/哈希有任何关系。让除用户以外的其他人看到/知道密码/哈希是一个严重的安全问题。

换个说明:您应该使用默认实现进行哈希处理。使用您自己的哈希算法总是比真正久经考验的方法更糟糕。我不确定您使用的是哪个 PHP 版本,但从 PHP 5.5 开始,您可以使用 password_hash() .有关更多信息,请查看此问题。