首页 > 解决方案 > 使用 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”对象没有属性“翻译”

标签: python-3.xfileencryptioncaesar-cipher

解决方案


当您以 e 打开文件然后调用 e.translate 时,您是在文件描述符上调用 translate,而不是内容。首先你需要阅读e的内容。


推荐阅读