认证中的bcrypt机制(不匹配哈希)

0 投票
1 回答
928 浏览
提问于 2025-04-17 07:58

我正在尝试用Python(pymongo)和bcrypt来实现一个MongoDB的登录方法。问题出现在我尝试比较哈希值时,它们总是不同的 :$。

这是我的测试代码(首先,我在MongoDB中放入了一个带有哈希密码的用户):

使用Python的scrypt:

bcrypt.hashpw('testpassword', bcrypt.gensalt(12))
'$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi'


db.users.insert({username: "yichuan",password: "$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi" });

一旦我们把它放进数据库,我就想试试这个魔法 :D:

def test_connectionManagerLoginPass(self):
    connectionmanager=dbconnection.ConnectionManager()
    username='yichuan'
    password='testpassword'
    hashed = bcrypt.hashpw(password, bcrypt.gensalt(12))
    self.assertIsNotNone(connectionmanager.login(username,hashed), 'No error espected in login') 

但是问题出现在我看到的哈希值上:

'$2a$12$hw1DaWdOf3ECBcSgu2GB4Of3oAdKvyzl0xftBVzbyqkjK2A3X.LOm'

它和我之前生成的完全不同!!!。我还读到我不需要保存bcrypt.gensalt(12)。所以我有点困惑。

感谢你的阅读,有谁能帮我看看我的认证实现哪里出了问题吗?

附言(更多代码)

def login(self,username,password):
    if self.loginfieldsfilter(username,password):
        dbdata = self.users.find_one({'username': username})
        if password == dbdata[ 'password' ]:
            return True
        else:
            return None 
    else:
        return None

而且,我确定数据库给我的字段是正确的。

1 个回答

2

在检查密码的时候,你需要把哈希值本身当作盐,因为它的开头部分就包含了盐。这有点让人困惑,但因为你必须使用相同的盐才能得到和之前一样的哈希值,所以这是唯一的方法:

>>> myhash = bcrypt.hashpw('testpassword', bcrypt.gensalt(12))
>>> myhash    
'$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi'
>>> bcrypt.hashpw('testpassword', myhash)
'$2a$12$K1hnCm5z74QtXaynv4.S8.i1FK9xjRr7JSPCRCyB9zpv8xZznZGFi'

(不过我只是通过复制和粘贴把这个组合起来的)

撰写回答