0

我的程序有问题,它所做的只是基于密钥加密和解密文本。但是,当我尝试解密加密的单词时,它只会吐出错误

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()

4

1 回答 1

2

我与您提供的代码不同。我想您已将无效值传递给 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'
于 2020-04-30T15:40:11.913 回答