BCrypt公司。如何用Python储存盐?

2024-05-14 03:30:37 发布

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

我们有代码,python 2。在

@password.setter
def password(self, value):
    self.salt = bcrypt.gensalt()
    self.passwd = bcrypt.hashpw(value.encode('utf-8'), self.salt)

def check_password(self, value):
    return bcrypt.hashpw(value.encode('utf-8'), self.salt.encode('utf-8')) == self.passwd

但是,当我试图将其转换为python3时,我们遇到了以下问题:

cassandra驱动程序级别出现错误一:

^{pr2}$

好吧。把盐和密码放在绳子上:

@password.setter
def password(self, value):
    salt = bcrypt.gensalt()
    self.salt = str(salt)
    self.passwd = str(bcrypt.hashpw(value.encode('utf-8'), salt))

现在盐省了。但是在check_password中我们得到ValueError: Invalid salt。 如果将检查密码代码更改为:

def check_password(self, value):
    return bcrypt.hashpw(value, self.salt) == self.passwd

我们得到错误TypeError: Unicode-objects must be encoded before hashing。在

去哪儿挖?在

UPD密码和检查密码中的Salt值看起来相同,例如:

b'$2b$12$cb03angGsu91KLj7xoh3Zu'                                                                        
b'$2b$12$cb03angGsu91KLj7xoh3Zu'

Tags: 代码self密码valuedefcheckpasswordutf
1条回答
网友
1楼 · 发布于 2024-05-14 03:30:37

更新

从版本3.1.0起,bcrypt提供了便利功能

checkpw(password, hashed_password)

对哈希密码执行密码检查。应使用此选项代替:

^{pr2}$

如下所示。仍然不需要单独存储散列。在


首先,不需要存储salt,因为它是bcrypt.hashpw()生成的散列的一部分。你只需要存储散列。E、 g

>>> salt = bcrypt.gensalt()
>>> salt
b'$2b$12$ge7ZjwywBd5r5KG.tcznne'
>>> passwd = b'p@ssw0rd'
>>> hashed_passwd = bcrypt.hashpw(passwd, salt)
b'$2b$12$ge7ZjwywBd5r5KG.tcznnez8pEYcE1QvKshpqh3rrmwNTQIaDWWvO'
>>> hashed_passwd.startswith(salt)
True

所以你可以看到盐包含在哈希中。在

您还可以使用bcrypt.hashpw()检查密码是否与哈希密码匹配:

>>> passwd_to_check = b'p@ssw0rd'
>>> matched = bcrypt.hashpw(passwd_to_check, hashed_passwd) == hashed_passwd
>>> matched
True
>>> bcrypt.hashpw(b'thewrongpassword', hashed_passwd) == hashed_passwd
False

不用单独存放盐。在


所以您可以这样编写setter(Python 3):

@password.setter
def password(self, passwd):
    if isinstance(passwd, str):
        passwd = bytes(passwd, 'utf-8')
    self.passwd = str(bcrypt.hashpw(passwd, bcrypt.gensalt()), 'utf8')

检查器是这样的:

def check_password(self, passwd_to_check):
    if isinstance(passwd_to_check, str):
        passwd_to_check = bytes(passwd_to_check, 'utf-8')
    passwd = bytes(self.passwd, 'utf8')
    return bcrypt.hashpw(passwd_to_check, passwd) == passwd

相关问题 更多 >