python - 引发 InvalidToken,cryptography.fernet.InvalidToken
问题描述
我的程序有问题,它所做的只是基于密钥加密和解密文本。但是,当我尝试解密加密的单词时,它只会吐出错误
raise InvalidToken
cryptography.fernet.InvalidToken
这是代码
#Import Libraries
from cryptography.fernet import Fernet
from tkinter import *
import base64
def Encrypt(text_f):
f = Fernet(b'eY_snWFGBTxC55GsmloucJhPtiLt_3bANhHnikOlXFQ=')
print(f.encrypt((str(text_f).encode())))
def Decrypt(text_f):
f = Fernet(b'eY_snWFGBTxC55GsmloucJhPtiLt_3bANhHnikOlXFQ=')
print(f.decrypt((bytes(text_f).encode())))
#Set Window
root = Tk()
#Define Elements
text_user = ""
instruction_1 = Label(root, text="Input Text")
text_input = Entry(root, textvariable=text_user)
button_encode = Button(root, text='Encode', command = lambda : Encrypt(str(text_user.encode())))
button_decode = Button(root, text='Decode', command = lambda : Decrypt(str(text_user.encode())))
text_description = Label(root, text="")
#Pack Elements
instruction_1.pack(ipady = 10, ipadx = 5)
text_input.pack(ipady = 5, ipadx = 4)
button_encode.pack(ipady = 3, ipadx = 12)
button_decode.pack(ipady = 3, ipadx = 12)
#Setup Window Properties
root.geometry('800x650')
root.title("APEP | Encoder & Decoder")
#Loop Window Runtime
root.mainloop()
解决方案
我与您提供的代码不同。我想您已将无效值传递给 Encrypt/Decrypt 函数。
我添加了一些更改:
#Import Libraries
from functools import partial
from cryptography.fernet import Fernet
from tkinter import *
import base64
key = Fernet.generate_key()
f = Fernet(key)
def Encrypt(text_f: Entry):
encrypted = f.encrypt(bytes(text_f.get(), 'utf-8'))
print("[*] Encrypted: {}".format(encrypted))
return encrypted
def Decrypt(text_f: Entry):
plain = f.decrypt(bytes(text_f.get(), 'utf-8'))
print("[*] Plain: {}".format(plain))
return plain
#Set Window
root = Tk()
#Define Elements
text_user = ""
instruction_1 = Label(root, text="Input Text")
text_input = Entry(root, textvariable=text_user)
button_encode = Button(root, text='Encode', command=partial(Encrypt, text_input))
button_decode = Button(root, text='Decode', command=partial(Decrypt, text_input))
text_description = Label(root, text="")
#Pack Elements
instruction_1.pack(ipady = 10, ipadx = 5)
text_input.pack(ipady = 5, ipadx = 4)
button_encode.pack(ipady = 3, ipadx = 12)
button_decode.pack(ipady = 3, ipadx = 12)
#Setup Window Properties
root.geometry('800x650')
root.title("APEP | Encoder & Decoder")
#Loop Window Runtime
root.mainloop()
我添加了partial
函数导入和从 Entry 小部件 (text_f.get()) 接收文本。
结果可能是您所期望的:
[*] Encrypted: b'gAAAAABequ_Y0sJVQVDTTcES3nHKm50gTlKqECPmEyLUgh3A1ehw0ANkKmk9PF3Y-vZ8wS6oGwvL6l432WiNO3U0LlTkD1ilhQ=='
[*] Plain: b'test'
推荐阅读
- r - 将 .ndjson 文件读入 R
- flutter - 不从 Firebase 检索 CurrentUser 特定数据 - Flutter
- sql - 通过语句计算从每个组中获得的平均值的平均值
- javascript - 如何进行长时间的网页加载?
- c - 如何使用 sprintf 显示 64 位无符号整数?
- vim - 在 Vim 中,在指定的跳转位置打开一个新窗口
- asp.net-mvc - ASP .NET CORE MVC 3.1 - 创建新 Intent 时出现 Invalid Column Name 错误
- laravel - 如何在 Ceate Crud 中显示仅选择启用的文件
- python - 如何仅在 Gitlab 中更改的文件上运行 pylint?
- visual-studio - Visual Basic - 从 FOR 循环中删除值