我想用bcrypt
来散列密码,然后验证提供的密码是否正确。如何使用bcrypt将纯文本密码与哈希密码进行比较?
哈希密码很简单:
import bcrypt
password = u'foobar'
password_hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# then store password_hashed in a database
我如何比较明文密码存储的散列?
我想用bcrypt
来散列密码,然后验证提供的密码是否正确。如何使用bcrypt将纯文本密码与哈希密码进行比较?
哈希密码很简单:
import bcrypt
password = u'foobar'
password_hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# then store password_hashed in a database
我如何比较明文密码存储的散列?
使用py-bcrypt,你不需要单独存储盐:bcrypt
将盐存储在散列中。
您可以简单地使用散列作为盐,并将盐存储在散列的开头。
>>> import bcrypt
>>> salt = bcrypt.gensalt()
>>> hashed = bcrypt.hashpw('secret', salt)
>>> hashed.find(salt)
0
>>> hashed == bcrypt.hashpw('secret', hashed)
True
>>>
稍后,假设您有一个用户输入密码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
后来时间:
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
谢谢。是新来这个,我完全失踪的事实,盐和密码需要被存储并随后进行比较。感谢堆! – MFB 2012-03-04 22:56:16
使用bcrypt时不需要存储盐。下面的答案是正确的。 – 2013-05-01 02:27:52
没有提到存储盐的文档,它说,你只需要:
#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"
每次调用bcrypt.gensalt()时都会生成新的salt,因此必须将salt与bcrypt.hashpw()的结果一起保存。 – skyler 2012-09-03 22:23:02
@skyler - 用bcrypt,盐被存储为散列的一部分。它被保存到散列中,并且自动将散列与它进行比较。 – 2012-10-22 00:31:12
我不熟悉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"
好的答案,但只是一个FYI,'哈希'是一个Python 2和3保留关键字(内建函数),并设置'哈希= ...'覆盖内置的任何范围内的内置。我会改变它像'hashed'或'pw_hash'等。 – alichaudry 2017-03-29 20:21:11
我同意。这个'hash'必须被其他名称替代:)。 – ivanleoncz 2017-10-02 21:09:27
不要忘记编码你的字符串,'secret'.encode()'。注意:在Python 3中测试。 – Yamaneko 2018-02-04 03:15:38