检查bcrypt密码总是失败的问题在Phalcon php中

5

我在使用Phalcon PHP检查bcrypted密码时遇到了一些问题。我有以下代码:

登录脚本中,我会检查密码:

$username = $this->request->getPost('username', 'string');
            $password = $this->request->getPost('password', 'string');
            $conditions = "Username = :username:";
            $parameters = array (
                "username" => $username
            );

            $user = Users::findFirst(array($conditions, 'bind' => $parameters));
            //check if user exists
            if (count($user) > 0 && $user !== false) {

                if ($this->security->checkHash($password, $user->Password))  //always fails {
                    //login 
                    $this->session->set('username', $user->Password);
                    $this->response->redirect('index');

                }

在我的注册表单中,我有以下内容:
$name = $this->request->getPost('name', 'string');
            $lastName = $this->request->getPost('lastName', 'string');
            $username = $this->request->getPost('username', 'string');
            $password = $this->request->getPost('password', 'string');
            $email = $this->request->getPost('email', 'email');

            $user = new Users(); //model
            $user->Name = $name;
            $user->LastName = $lastName;
            $user->Username = $username;
            $user->Password = $this->security->hash($password);
            $user->Email = $email;
            if ($user->save() == true) {
                //registered
            } else {
                //error
            }

看起来我按照 文档 做了一切,但好像不起作用。请问有人能帮帮我吗。


你有没有兴趣追踪一下你数据库中存储的密码,以及在 $user->Password 中接收到的密码和 $this->security->hash($password); 产生的哈希值是否匹配?它们是否相同? - Ian Bytchek
另外,您确定要在这里设置正确的内容吗?$this->session->set('username', $user->Password); - Ian Bytchek
我在数据库中有一个用户名为“jt26”的用户。我尝试在我的控制器中调用die($this->security->hash('jt26'));来查看密码。但是每次它都会产生不同的字符串。这样正常吗? - Andriy Haydash
很多时候,保存BCrypt哈希的数据库字段太小了,应该能够存储60个字符的字符串。 - martinstoeckli
对我来说,Phalcon也会为相同的密码生成不同的哈希结果。请告诉我我错过了什么。 - Tuyen Nguyen
1个回答

0

在您的数据库中,存储的密码必须是jt26的加密值,即$this->security->hash('jt26')的乘积。可能您首先存储了密码,然后再实现注册/登录功能。只需在数据库中用由$this->security->hash('jt26')生成的字符串替换jt26,一切都应该开始运作。

它每次都产生不同的字符串。这样做对吗?

是的,这正是它应该做的。有关详细信息,请参见this。盐始终是随机生成的(除非提供),基于此生成散列。在验证密码时,Bcrypt使用盐重新生成哈希,然后检查其是否匹配。


1
我还没有先插入密码。我已经使用我上面提供的注册脚本完成了这个步骤。我按照文档进行了操作,但是它并没有起作用。可能有一个愚蠢的问题,但我找不到它。 - Andriy Haydash
你尝试创建一个新用户了吗?如果一切都像你描述的那样工作,在执行 $user->save() 之前,$user->Password 的值必须是一个有效的哈希值。如果用户成功保存,则数据库中的值也必须是相同的有效哈希值,而不是 jt26。要么你在此之前做错了什么,要么你正在做其他事情,导致在你的数据库中存储了不同的值。 - Ian Bytchek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接