我想用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)
小智 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/
稍后,假设您有一个用户输入密码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)
我不熟悉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)