PHP Bcrypt转向Python3

时间:2014-07-18 13:19:39

标签: python-3.x bcrypt blowfish

我需要将原始的php auth验证移动到python3。我有这样的代码:

// hash from db
$hash = "$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e";

// the hash is used as salt
$result = crypt($password, $hash);

//result should match the hash if pasword is correct 
$result = "$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e";

使用参数cost = 14

完成

在python3中实现它的最佳库是什么?

EDITED: 我使用了lib py-bcrypt

>>> import bcrypt  
>>> password = "ahoj"
>>> db_hash = "$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e"
>>> computed_hash = bcrypt.hashpw(password, db_hash)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Invalid salt

为什么盐无效?

在PHP中它起作用:

password=ahoj
hash=$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e
result=$2y$14$00sMXcXPyTthEv9m5dszwuT8VUU6KK1HtCunemfutphrbCHZoIz0e

python有什么不同?

1 个答案:

答案 0 :(得分:1)

如果您想比较密码,请使用checkpw功能代替hashpw

if bcrypt.checkpw(passsword, db_hash):
    print "It matches"
else:
    print "It does not match"

只有在生成新哈希时才需要Salt:

hashed = bcrypt.hashpw(password, bcrypt.gensalt())

您可以在README文件中找到更多详细信息。