使用Python的密钥导出函数(密钥.导出.函数.Python...)

wufei1232025-01-24python11

欢迎来到下一个 pikotutorial!

在之前的一篇文章中,我们学习了如何使用 python 执行对称数据加密。最后一个示例是将用户提供的密码直接转换为加密密钥。尽管它有效,但这不是推荐的方法。今天给大家推荐一个密钥导出函数。

密钥导出函数

下面您可以找到如何在 python 中使用 pbkdf2hmac 密钥导出函数的扩展示例:

# 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'' * 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的密钥导出函数的详细内容,更多请关注知识资源分享宝库其它相关文章!

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。