我想使用bcrypt
哈希密码,然后验证提供的密码是否正确。
哈希密码很简单:
import bcrypt
password = u'foobar'
password_hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# then store password_hashed in a database
如何将纯文本密码与存储的哈希值进行比较?
答案 0 :(得分:57)
使用py-bcrypt,您不需要单独存储盐:bcrypt
将盐存储在哈希中。
您可以简单地将哈希用作salt,并将salt存储在哈希的开头。
>>> import bcrypt
>>> salt = bcrypt.gensalt()
>>> hashed = bcrypt.hashpw('secret', salt)
>>> hashed.find(salt)
0
>>> hashed == bcrypt.hashpw('secret', hashed)
True
>>>
答案 1 :(得分:14)
文档中没有提到存储盐,它说你必须:
#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"
答案 2 :(得分:5)
稍后,假设您有一个用户输入密码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
答案 3 :(得分:2)
我不熟悉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"
答案 4 :(得分:0)
我认为这个会更好:
for i in range(len(rserver.keys())):
salt = bcrypt.gensalt(12)
mdp_hash = rserver.get(rserver.keys()[i])
rserver.set(rserver.keys()[i], bcrypt.hashpw(mdp_hash.encode(),bcrypt.gensalt(12) ))
rsalt.set(rserver.keys()[i], salt)