如何使用bcrypt将纯文本密码与散列密码进行比较?

MFB*_*MFB 36 python bcrypt

我想用bcrypt哈希密码,然后验证提供的密码是否正确.

散列密码很简单:

import bcrypt

password = u'foobar'
password_hashed = bcrypt.hashpw(password, bcrypt.gensalt())

# then store password_hashed in a database
Run Code Online (Sandbox Code Playgroud)

如何将纯文本密码与存储的哈希进行比较?

小智 60

使用py-bcrypt,您不需要单独存储salt:bcrypt将salt存储在哈希中.

您可以简单地将哈希用作salt,并将salt存储在哈希的开头.

>>> import bcrypt
>>> salt = bcrypt.gensalt()
>>> hashed = bcrypt.hashpw('secret', salt)
>>> hashed.find(salt)
0
>>> hashed == bcrypt.hashpw('secret', hashed)
True
>>>
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案,但只是一个FYI,`hash`是一个Python 2和3保留关键字(builtin func),设置`hash = ...`会覆盖你所处的任何范围的内置.我会改变它的东西比如`hashed`或`pw_hash`等 (5认同)
  • 不要忘记编码你的字符串,`'secret'.encode()`.注意:在Python 3中测试过. (4认同)

小智 16

文档没有提到存储盐,它说你必须:

#Initial generation
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
#Store hashed in your db

#Load hashed from the db and check the provided password
if bcrypt.hashpw(password, hashed) == hashed:
    print "It matches"
else:
    print "It does not match"
Run Code Online (Sandbox Code Playgroud)

http://www.mindrot.org/projects/py-bcrypt/

  • @skyler - 使用bcrypt,salt存储为哈希的一部分.它被保存到哈希中,并自动将哈希与它进行比较. (8认同)
  • 将哈希值与“==”进行比较会引入安全问题(计时攻击)。您应该使用“hmac.compare_digest”。 (4认同)

Amb*_*ber 6

稍后,假设您有一个用户输入密码user_pass.你也要哈希,然后将哈希与存储的哈希进行比较,如果它们匹配,那么原始密码也匹配.

请注意,bcrypt会自动将salt值存储为散列密码的一部分,以便您在散列未来输入时也可以使用它.

第一次:

import bcrypt

password = u'foobar'
salt = bcrypt.gensalt()
password_hashed = bcrypt.hashpw(password, salt)

# store 'password_hashed' in a database of your choosing
Run Code Online (Sandbox Code Playgroud)

以后的时间:

import bcrypt
password = something_that_gets_input()

stored_hash = something_that_gets_this_from_the_db()

if bcrypt.hashpw(password, stored_hash) == stored_hash:
    # password matches
Run Code Online (Sandbox Code Playgroud)

  • 使用bcrypt时无需存储盐.下面的答案是正确的. (3认同)

Gov*_*ngh 6

我不熟悉Python,但我认为你可以使用:
public static boolean checkpw(java.lang.String plaintext, java.lang.String hashed)

# Check that an unencrypted password matches one that has  
# previously been hashed.
if bcrypt.checkpw(plaintext, hashed):
    print "It matches"
else:
    print "It does not match"
Run Code Online (Sandbox Code Playgroud)