验证 python-pbkdf2 中的 PBKDF2 密码哈希

Verifying a PBKDF2 password hash in python-pbkdf2

我正在使用下面的代码片段在保存到数据库之前加密用户密码。

from pbkdf2 import crypt
pwhash = crypt(password_from_user)

示例:$p5k2$$Y0qfZ64u$A/pYO.3Mt9HstUtEEhWH/RXBg16EXDMr

然后,我将其保存在数据库中。那么在本地,我可以执行这样的检查:

from pbkdf2 import crypt
  pwhash = crypt("secret")
  alleged_pw = raw_input("Enter password: ")
  if pwhash == crypt(alleged_pw, pwhash):
      print "Password good"
  else:
      print "Invalid password"

但是我该如何检查数据库中的内容,因为加密的字符串并不总是相同的。我正在使用 python-pbkdf2.

好吧,经过更多研究发现要实现这一点,我首先必须加密密码并保存在 db.as:

pwhash = crypt("secret",iterations=1000)

可以生成类似 $p5k2e8$her4h.6b$.p.OE5Gy4Nfgue4D5OKiEVWdvbxBovxm

的字符串

为了验证用户何时想使用相同的密码登录,我使用以下函数:

def isValidPassword(userPassword,hashKeyInDB):
     result = crypt(userPassword,hashKeyInDB,iterations = 1000)
     return reesult == hashKeyInDB #hashKeyInDB in this case is $p5k2e8$her4h.6b$.p.OE5Gy4Nfgue4D5OKiEVWdvbxBovxm

此方法 returns True 如果密码相同或 False 否则。