欢迎来到下一个 pikotutorial!
在之前的一篇文章中,我们学习了如何使用 python 执行对称数据加密。最后一个示例是将用户提供的密码直接转换为加密密钥。尽管它有效,但这不是推荐的方法。今天给大家推荐一个密钥导出函数。
下面您可以找到如何在 python 中使用 pbkdf2hmac 密钥导出函数的扩展示例:
bee餐饮点餐外卖小程序是针对餐饮行业推出的一套完整的餐饮解决方案,实现了用户在线点餐下单、外卖、叫号排队、支付、配送等功能,完美的使餐饮行业更高效便捷!功能演示:1、桌号管理登录后台,左侧菜单 “桌号管理”,添加并管理你的桌号信息,添加以后在列表你将可以看到 ID 和 密钥,这两个数据用来生成桌子的二维码2、生成桌子二维码例如上面的ID为 308,密钥为 d3PiIY,那么现在去左侧菜单微信设置
1
# import utility for Base64 encoding
import base64
# import Fernet
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
# import getpass for secure input reading
from getpass import getpass
# read plain text password
plain_text_password: str = getpass(prompt='Password: ')
# convert the password to bytes
password_bytes = plain_text_password.encode('utf-8')
# some salt value for demonstration, use a secure random value in practice
salt = b'\x00' * 16
# use PBKDF2HMAC to derive a secure key from the password
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000
)
# encode the derived key with Base64
key = base64.urlsafe_b64encode(kdf.derive(password_bytes))
# create a Fernet instance with the derived key
fernet = Fernet(key)
# data to be encrypted
data = b'Some secret data'
# encrypt the data
encrypted_data = fernet.encrypt(data)
# decrypt the data
decrypted_data = fernet.decrypt(encrypted_data)
# print the decrypted data
print(f"Decrypted text: {decrypted_data.decode()}")
以这种方式创建的密钥不仅更安全,而且不再要求纯文本密码长度恰好为 32 个字节。
初学者注意事项:记住加盐是解密数据所必需的!
以上就是使用Python的密钥导出函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号