我是tkinter
库的新手。我已经搜索了足够的内容并调试了几个小时,但无法弄清楚解密为何不起作用。但是,如果不使用tkinter
,则代码可以正常工作。
代码如下:
from cryptography.fernet import Fernet
key = Fernet.generate_key() # to make a key or to genrate a key
print(key)
from tkinter import *
root=Tk()
def clicked():
input1 = ent1.get()
FileName = str(input1)
TextFile = open(FileName,"w")
input2 = ent2.get()
wrcont = str(input2)
TextFile.write(wrcont)
TextFile.close()
b1 = Button(root, text='SUBMIT',bg='light blue',fg='green',command=clicked)
b1.grid(row=2,sticky=E)
def encryption():
print('In Encryption')
input1 = ent1.get()
FileName = str(input1)+".txt"
TextFile = open(FileName,"w")
with open(FileName,'rb') as TextFile:
data = TextFile.read()
fernet = Fernet(key)
encrypted = fernet.encrypt(data)
decrypted = fernet.decrypt(encrypted)
print(encrypted)
print('Decrypted')
print(decrypted)
TextFile.close()
print(key)
with open(FileName, 'wb') as TextFile:
TextFile.write(encrypted)
TextFile.close()
b2 = Button(root,text='ENCRYPT',bg='red',command=encryption)
b2.grid(row=4,column=2)
#for decryption
# open the file to decryption
def decryption():
input1 = ent1.get()
file = str(input1)+".txt"
#TextFile = open(file)
print('In Decryption')
print(file)
with open(file,'rb') as TextFile:
token = TextFile.read()
TextFile.close()
print(token)
#print(data)
print(key)
fernet = Fernet(key)
decrypted = fernet.decrypt(token)
print('decrypted data')
print(decrypted)
# write the encrypted file
file = file+"dec"
with open(file, 'wb') as TextFile:
TextFile.write(decrypted)
TextFile.close()
b3 = Button(root,text='DECRYPT',bg='red',command=decryption)
b3.grid(row=5,column=2)
l4 = Label(root,text='Enter file Name to Decrypt:',bg='light blue')
ent4 = Entry(root)
l4.grid(row=5,sticky=S)
ent4.grid(row=5,column=1)
l1 = Label(root, text='Enter your file name:',bg='light blue')
l2 = Label(root, text='Write some text into file:',bg='light blue')
ent1 = Entry(root)
ent2 = Entry(root)
l1.grid(row=0,sticky=E)
l2.grid(row=1,sticky=E)
ent1.grid(row=0,column=1,sticky=E)
ent2.grid(row=1,column=1,sticky=E)
l3 = Label(root, text='Enter file to encrypt:',bg='light blue')
ent3 = Entry(root)
l3.grid(row=4,sticky=E)
ent3.grid(row=4,column=1)
root.title('FILE ENC/DEC')
root.geometry('800x500')
root.configure(background='purple')
root.mainloop()
输出(控制台):
b'QsQpCVnYOIQcdG-JjAwi_sw3Qqc7fB6eyeQ8zf9oPs4='
In Encryption
b'gAAAAABcrtxDIgMvDsYAV6GzpVVE3UYLZtwArC07E8johAQgOTbLUwjCJab1A4UnniZbtJOJiepRHcX04xKnCcdbpFktTHsqcQ=='
Decrypted
b''
b'QsQpCVnYOIQcdG-JjAwi_sw3Qqc7fB6eyeQ8zf9oPs4='
In Decryption
aaa.txt
b'gAAAAABcrtxDIgMvDsYAV6GzpVVE3UYLZtwArC07E8johAQgOTbLUwjCJab1A4UnniZbtJOJiepRHcX04xKnCcdbpFktTHsqcQ=='
b'QsQpCVnYOIQcdG-JjAwi_sw3Qqc7fB6eyeQ8zf9oPs4='
decrypted data
b''
任何帮助深表感谢。
答案 0 :(得分:0)
您的加密功能中的行TextFile = open(FileName,"w")
不正确,并导致了此错误。当您使用w
打开要写入的文件时,该文件将立即被截断,因此所有内容都会丢失。然后,下一行在二进制读取模式下将其重新打开,但此时它将仅读取一个空字节字符串。然后,您的fernet实例会加密空字节字符串,解密后您(正确)看不到任何内容。