如何使用bcrypt比较纯文本密码和散列密码?

2024-04-20 11:23:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用bcrypt来散列密码,然后验证提供的密码是否正确。

散列密码很简单:

import bcrypt

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

# then store password_hashed in a database

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


Tags: storein文本import密码passworddatabasefoobar
3条回答

文件中没有提到储存盐,只是说你必须:

#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"

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

以后的时间:

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

使用py bcrypt,不需要单独存储盐:bcrypt将盐存储在散列中。

您可以简单地将散列用作盐,盐存储在散列的开头。

>>> import bcrypt
>>> salt = bcrypt.gensalt()
>>> hashed = bcrypt.hashpw('secret', salt)
>>> hashed.find(salt)
0
>>> hashed == bcrypt.hashpw('secret', hashed)
True
>>>

相关问题 更多 >