PHP:从哈希解密密码 [英] PHP : Decrypt password from hash

查看:58
本文介绍了PHP:从哈希解密密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, I successfully encrypt a password to password hash using this following code :

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);
    }

}

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

and this is how I encrypting the password :

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

但是当我尝试以普通模式显示密码时,我现在有一个小问题.

But I have a little problem now when I try to display the password in normal mode.

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

What is the best way to decrypt the password from that hash ?

推荐答案

您不能解密哈希(嗯...从技术上来说,您可以,但您不应该),这就是哈希为(不解密).您需要使用与存储的哈希相同的哈希算法对收到的密码进行加密(哈希),然后将哈希相互比较.

You can't decrypt a hash (well... technically you can, but you shouldn't) that's what hashes are for (not to be decrypted). You'll want to encrypt(hash) the password you received with the same hashing algorithm you used for the stored hash, and compare the hashes with eachother.

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

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

All in all you don't want to let anyone (not even yourself) know what the password of a user is (or the hash for that matter). The user will know, because he entered it and remembers it (hopefully anyway). No one else has got anything to do with seeing the user's password/hash. Letting anyone else but the user see/know the password/hash is a serious security issue.

另一方面,您应使用默认实现进行哈希处理.使用您自己的哈希算法总是比真正的尝试和测试方法更糟糕.我不确定您使用的是哪个PHP版本,但是从PHP 5.5起,您可以使用问题.

On a different note: You should use the default implementations for hashing. Using your own hashing algorithm will always be worse than the true tried and tested methods. I'm not sure what PHP version you're using, but from PHP 5.5 onwards you can use password_hash(). For more information please view this question.

这篇关于PHP:从哈希解密密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆