首页 > 解决方案 > 无法使用 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.')

标签: pythonencryptioncryptography

解决方案


问题在于,每次执行程序时,都会生成一个新密钥。的问题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.')

推荐阅读