Nik*_*nyh 6 python bcrypt python-2.7 python-3.x
我们有代码,适用于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
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试将其转换为python3时,我们遇到以下问题:
在cassandra驱动程序级别发生错误:
cassandra.cqlengine.ValidationError: passwd <class 'bytes'> is not a string
Run Code Online (Sandbox Code Playgroud)
好.将salt和passwd转换为字符串:
@password.setter
def password(self, value):
salt = bcrypt.gensalt()
self.salt = str(salt)
self.passwd = str(bcrypt.hashpw(value.encode('utf-8'), salt))
Run Code Online (Sandbox Code Playgroud)
现在盐节省了.但是check_password我们得到了ValueError: Invalid salt.如果我们将检查密码更改为:
def check_password(self, value):
return bcrypt.hashpw(value, self.salt) == self.passwd
Run Code Online (Sandbox Code Playgroud)
我们得到错误TypeError: Unicode-objects must be encoded before hashing.
在哪里挖?
密码和检查密码中的UPD Salt值看起来相同,例如:
b'$2b$12$cb03angGsu91KLj7xoh3Zu'
b'$2b$12$cb03angGsu91KLj7xoh3Zu'
Run Code Online (Sandbox Code Playgroud)
mha*_*wke 11
更新
从3.1.0版开始bcrypt提供了便利功能
checkpw(password, hashed_password)
Run Code Online (Sandbox Code Playgroud)
根据哈希密码执行密码检查.这应该用来代替:
bcrypt.hashpw(passwd_to_check, hashed_passwd) == hashed_passwd
Run Code Online (Sandbox Code Playgroud)
如下所示.仍然无需单独存储哈希.
首先,您不需要存储salt,因为它是由生成的哈希的一部分bcrypt.hashpw().你只需要存储哈希.例如
>>> 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
Run Code Online (Sandbox Code Playgroud)
所以你可以看到盐包含在哈希中.
您还可以使用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
Run Code Online (Sandbox Code Playgroud)
无需单独存放盐.
所以你可以像这样编写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')
Run Code Online (Sandbox Code Playgroud)
检查器是这样的:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3637 次 |
| 最近记录: |