在本文中,我们将探讨如何使用 BCrypt 在 Python 中对密码进行哈希处理。以明文形式存储密码是一种糟糕的安全实践,因为它容易受到各种黑客攻击的侵扰。这就是为什么建议将密码以哈希(Hash)形式保存的原因。
什么是哈希?
这是使用哈希函数将一个字符串转换为另一个字符串的过程。哈希函数有多种类型,但它们都有一些基本的相似之处,即哈希是一个不可逆的过程。也就是说,转换应该是单向的,哈希的长度应该是固定的,并且输入字符串应该与哈希值唯一对应,以便我们随后进行比较,这使其成为密码和身份验证的理想选择。
!Hashing Passwords in Python with BCrypt
Bcrypt 是一种由 Nelis Provos 和 David Mazières 设计的密码哈希函数。Bcrypt 使用强大的加密技术基于 Blowfish 密码对密码进行哈希和加盐处理。为了增强加密强度,我们可以增加“成本因子”,这样随着计算机速度的加快,我们也可以相应提高安全等级。该函数还被设计为缓慢运行,以使暴力破解攻击变得更慢、更困难。
要安装 Bcrypt,请使用以下命令 –
pip install bcrypt
Bcrypt 中使用的函数包括 –
- bcrypt.gensalt() – 它用于生成盐。盐是添加到密码中的伪随机字符串。由于哈希对于相同的输入总是产生相同的输出,因此如果有人可以访问数据库,哈希可能会被破解。为此,在哈希之前将盐添加到密码的末尾。它不需要任何参数,并返回一个伪随机字符串。
- bcrypt.hashpw() – 它用于创建存储在数据库中的最终哈希值。
- 参数 – 我们可以以字节码的形式传递盐和密码。
- 返回值 – 如果哈希成功,它返回一个哈希字符串。
要使用 bcrypt,你需要导入 bcrypt 模块。之后,bcrypt.hashpw() 函数接受 2 个参数:一个字符串(字节)和盐。盐是哈希函数中使用的随机数据。让我们在下面的示例中对一个密码进行哈希并打印它。
示例 1:
Python3
import bcrypt
# example password
password = ‘password123‘
# converting password to array of bytes
bytes = password.encode(‘utf-8‘)
# generating the salt
salt = bcrypt.gensalt()
# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
print(hash)
Output:
示例 2:
现在让我们稍微更改一下输入密码,以观察哈希的行为。
Python3
import bcrypt
# example password
password = ‘passwordabc‘
# converting password to array of bytes
bytes = password.encode(‘utf-8‘)
# generating the salt
salt = bcrypt.gensalt()
# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
print(hash)
Output:
验证密码
下面的示例对照哈希值检查密码。
示例 1:
在这里,我们将检查用户是否输入了正确的密码,为此我们可以使用 bcrypt.checkpw(password, hash)。首先,让我们假设用户输入了错误的密码。
Python3
import bcrypt
# example password
password = ‘passwordabc‘
# converting password to array of bytes
bytes = password.encode(‘utf-8‘)
# generating the salt
salt = bcrypt.gensalt()
# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
# Taking user entered password
userPassword = ‘password000‘
# encoding user password
userBytes = userPassword.encode(‘utf-8‘)
# checking password
result = bcrypt.checkpw(userBytes, hash)
print(result)
Output:
示例 2:
现在让我们看看密码匹配时会发生什么:
Python3
import bcrypt
# example password
password = ‘passwordabc‘
# converting password to array of bytes
bytes = password.encode(‘utf-8‘)
# generating the salt
salt = bcrypt.gensalt()
# Hashing the password
hash = bcrypt.hashpw(bytes, salt)
# Taking user entered password
userPassword = ‘passwordabc‘
# encoding user password
userBytes = userPassword.encode(‘utf-8‘)
# checking password
result = bcrypt.checkpw(userBytes, hash)
print(result)
Output: