0
import bcrypt

hashedstring = bcrypt.gensalt()
password = bcrypt.hashpw(password,hashedstring)

我是否应该每次在数据库表字段中保存散列字符串以在下次获取散列字符串时成功登录?

或者我应该在代码中使用静态预生成的散列字符串?

4

2 回答 2

3

您用于散列密码的盐存储在生成的散列中 - 这意味着无需将其存储在数据库中,因为它可以从散列中恢复。

根据项目页面,可以这样做:

# Store a hash.
import bcrypt
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
store_in_db(user, hashed) #Where user is the user to load the hash for, and store_in_db does what it says on the tin.

# Check against an existing hash
import bcrypt
hashed = load_from_db(user) # (get the password of the user from database) Where user is the user to load the hash for, and load_from_db does what it says on the tin.
if bcrypt.hashpw(password, hashed) == hashed: # Where password is a plaintext password attempt.
        print "It matches"
else:
        print "It does not match"

是的,你应该为每个值使用不同的盐——这是 BCrypt 的设计所鼓励的。

于 2012-01-15T14:11:27.233 回答
1

简短的回答:为每个密码使用新的盐。(编辑:使用 bcrypt 你不需要单独存储盐)

想象一下,如果攻击者从网站获取密码数据库。如果所有密码都使用普通盐进行哈希处理,那么攻击者可以很容易地找到使用普通密码的人:

hashedpwd = somehash('swordfish' + salt)

然后只需要一个数据库查询就可以找到使用“swordfish”作为密码的每个人。总会有相当一部分用户使用非常常见的密码。

另一方面,如果每个密码都有自己的盐,并且数据库中有 100 万个密码,攻击者必须计算 100 万个哈希值才能只检查一个密码,因此更加安全。

于 2012-01-15T14:17:34.960 回答