python - 无法使用 Fernet 解密数据 - 类型错误:令牌必须是字节
问题描述
我正在尝试制作简单的加密/解密 cli 脚本。解码加密文本时出现错误。
TypeError:令牌必须是字节
如果我使用str.encode(textToDecrypt)
或bytes(textToDecrypt, 'utf-8')
得到:
cryptography.fernet.InvalidToken
from cryptography.fernet import Fernet
fernet = Fernet(myKey)
selectedOption = input('\nSelect an option\n1. Encrypt\n2. Decypt\n')
if selectedOption == '1':
textToEncrypt = input('\nEnter the text to encrypt\n')
print(fernet.encrypt(textToEncrypt.encode()))
elif selectedOption == '2':
textToDecrypt = input('\nEnter the text to decrypt\n')
print(fernet.decrypt(textToDecrypt).decode())
else:
print('Please select a valid option.')
解决方案
问题在于,每次执行程序时,都会生成一个新密钥。的问题bytes
已解决encode
,但关键是出现错误。
这是因为当您按 1 并加密字符串时,程序结束。由于密钥没有存储在任何地方,因此密钥丢失了。
现在,如果您尝试使用新密钥解密加密消息,则会引发错误。
你可以试试这个:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
fernet = Fernet(key)
while True:
selectedOption = input('\nSelect an option\n1. Encrypt\n2. Decypt\n3. Generate new key\n4. Quit\n')
if selectedOption == '1':
textToEncrypt = input('\nEnter the text to encrypt\n')
print(fernet.encrypt(textToEncrypt.encode()))
elif selectedOption == '2':
textToDecrypt = input('\nEnter the text to decrypt\n')
print(fernet.decrypt(textToDecrypt.encode()).decode())
elif selectedOption == '3':
print("Generating new key...")
key = Fernet.generate_key()
fernet = Fernet(key)
print("New key is generated.")
elif selectedOption == '4':
print("Thank you. Bye.")
break
else:
print('Please select a valid option.')
推荐阅读
- python - python Kivy:按钮触发事件
- asp.net-core - 在断开连接的服务器上构建 .Net Core Web App 时出现 NuGet 问题
- sql - 每组 SQL Server 2019 随机数
- python - Stepfunction 将 lambdas 的输出传递给另一个 lamabda
- python - 可变长度消息的 TCP 传输
- r - R dplyr 如何根据单元格值修剪数据集?
- asp.net-core - SignalR 集线器重复连接 POST 请求
- postgresql - 为什么不应用优化/使用不同的索引?
- javascript - 为什么对象在vue中变成代理对象?
- api - 如何以编程方式查找触发 Windows 更新的 USB 设备?