python-3.x - 使用 Caesar Cipher 加密现有的 txt 文件
问题描述
我正在做一个小型家庭项目,我需要加密用户输入的文本。文本文件是在程序 def personal_save() 的第一部分创建的:但我想要实现的是,当用户按下主页上的关闭按钮时,def file_Encryption 读取生成的 txt 文件并对其进行加密。我已经找到了一个简单加密的代码,并试图更改代码但没有运气,因为我是编程世界的新手。
当用户按下退出按钮时,我创建了一个函数,然后应该使用静态加密密钥对文件进行加密,然后应该关闭根窗口。
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry('1030x400')
Label(root, bg="black").place(x=0, y=0)
fname = StringVar(root, value="Your first name")
lastname = StringVar(root, value="Your last name")
def personal_info():
persinf = Toplevel(root)
persinf.geometry('800x500')
persinf.configure(background="light blue")
ttk.Entry(persinf, textvar=fname).place(x=40, y=110)
ttk.Entry(persinf, textvar=lastname).place(x=240, y=110)
Button(persinf, text='Save', width=15, bg='brown', fg='black', command=personal_save).place(x=580, y=450)
def personal_save():
with open('Personal information.txt', 'a') as f:
line = f'{fname.get()}, {lastname.get()}\n'
f.write(line)
def file_ecryption():
with open('Personal information.txt', 'r') as e:
encryption_key = 2
lowerAlpha = "abcdefghijklmnopqrstuvwxyz"
upperAlpha = lowerAlpha.upper()
numbers = "0123456789"
decrypted = lowerAlpha + upperAlpha + numbers
encrypted = lowerAlpha[encryption_key:] + lowerAlpha[:encryption_key] + \
upperAlpha[encryption_key:] + upperAlpha[:encryption_key] + \
numbers[encryption_key:] + numbers[:encryption_key]
translation = str.maketrans(decrypted, encrypted)
cipherText = e.translate(translation)
print("\nCoded Message: {}".format(cipherText))
print("\nFrom: {}".format(decrypted))
print(" To: {}\n".format(encrypted))
print("Encryption key:", encryption_key)
root.destroy()
Button(root, text='Add personal information', width=25, bg='brown', fg='black', command=personal_info).\
place(x=50, y=200)
Button(root, text='Close window', width=25, bg='brown', fg='black', command=file_ecryption).\
place(x=200, y=200)
root.mainloop()
cipherText = e.translate(translation)
AttributeError:“_io.TextIOWrapper”对象没有属性“翻译”
解决方案
当您以 e 打开文件然后调用 e.translate 时,您是在文件描述符上调用 translate,而不是内容。首先你需要阅读e的内容。
推荐阅读
- flash - JSFL (Adobe animate) 导入嵌入视频,无需视频向导
- recaptcha - 达到 recaptchaV3 每月配额时会发生什么?
- angular - 扩展动态加载的嵌套树节点时如何等待子加载完成
- css - flexbox 项目没有扩展到它们的最大宽度
- arrays - 想要根据用户输入为带有参数的单元格生成链接
- java - 通过循环创建多个按钮
- kubernetes - 如何让 AKS 上的两个 HAProxy 入口控制器之一处理单个入口?
- java - JMeter java.lang.VerifyError:无法从最终类继承
- reactjs - Graphql 端点在失眠症和邮递员中工作,但在尝试获取数据时不在反应应用程序上。有什么建议么?
- python - 发布相同的按摩时,Django 'UNIQUE 约束失败'