Python实现文件访问和加密GUI应用程序

Python实现文件访问和加密

简单的文本文件加密和解密的GUI应用程序,实现了一个简单的凯撒密码加密和解密算法

运行效果

1.实现UI界面

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yG28ajb1-1720676735133)(https://i-blog.csdnimg.cn/direct/e5130309995b46279478a09dd013c689.png)]

2.打开原始文件,显示的文件名和文件内容正确。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QhQldndf-1720676735135)(https://i-blog.csdnimg.cn/direct/cd86486c99fd4250bd37fc7d89302ffb.png)]

3. 对照原始文件,加密文件正确

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V1pBHV4D-1720676735136)(https://i-blog.csdnimg.cn/direct/6e6b8a4bd0fe4d5bb280b5923f003047.png)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qekLqZO3-1720676735136)(https://i-blog.csdnimg.cn/direct/60a3b76e467d4d80b488498f2695cd68.png)]

4. 对照原始文件,解密文件一致

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5xguLPdD-1720676735137)(https://i-blog.csdnimg.cn/direct/7098e13c57e14097bf47933c7cf6a8f7.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Shk3FOQl-1720676735138)(https://i-blog.csdnimg.cn/direct/a21a85c406384c1cbe4a6b55d3babca9.png)]

5.测试使用不同的秘钥进行加密解密,结果正确

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vXF6sfK7-1720676735138)(https://i-blog.csdnimg.cn/direct/079dcb23a6454d7cb32778fa93fd8907.png)]

6. 对程序进行错误测试

6.1 没有打开文件直接进行加密,程序不应崩溃。
6.2 没有打开文件直接进行解密,程序不应崩溃。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nn4VMZwl-1720676735139)(https://i-blog.csdnimg.cn/direct/5ee623222a62464c867c57d42ab3ae12.png)]

6.3 没有设定秘钥直接进行加密,程序不应崩溃。
6.4 没有设定秘钥直接进行解密,程序不应崩溃。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-g3dPN9bk-1720676735139)(https://i-blog.csdnimg.cn/direct/aeb6b2e4fa794dfab70def9f1d5b8b30.png)]

6.5 秘钥设定错误,进行加密,程序不应崩溃。
6.6 秘钥设定错误,进行解密,程序不应崩溃。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HD2QHdUp-1720676735141)(https://i-blog.csdnimg.cn/direct/4ae9ce7dd9534ea093f7f78fa84a2a46.png)]

代码

导入必要的库和模块

from tkinter import *:导入Tkinter库,这是Python的标准GUI库。
from tkinter.filedialog import askopenfilename, asksaveasfilename:导入Tkinter库中用于选择文件和保存文件的对话框功能。
from Caesar import Caesar:导入自定义的Caesar密码算法类。

FileEncryptWindow类:

创建了Tkinter窗口并添加了两个Frame容器,分别用于文件名输入和密钥输入。
在文件名输入区域,有一个Entry控件用于显示选择的文件名,以及一个"打开"按钮触发openFile方法来选择要加密/解密的文件。
在密钥输入区域,有一个Entry控件用于输入密钥(默认为3),以及"加密"和"解密"按钮分别触发encryptFile和decryptFile方法。
在窗口底部,有一个Text控件用于显示文件的内容。

class FileEncryptWindow():
    def __init__(self):
        window = Tk()

        frame1 = Frame(window)
        frame1.pack()
        labelFileName = Label(frame1, text="文件名:", )
        labelFileName.grid(row=0, column=0)
        self.fileName = StringVar()
        entryFileName = Entry(frame1, width=100, textvariable=self.fileName)
        entryFileName.grid(row=0, column=1)
        btnOpen = Button(frame1, text="打开", command=self.openFile)
        btnOpen.grid(row=0, column=2)

        frame2 = Frame(window)
        frame2.pack()
        labelKey = Label(frame2, text="密钥:", )
        labelKey.grid(row=1, column=0)
        self.key = StringVar()
        entryKey = Entry(frame2, textvariable=self.key)
        self.key.set("3")
        entryKey.grid(row=1, column=1)
        btnEncrypt = Button(frame2, text="加密", command=self.encryptFile)
        btnEncrypt.grid(row=1, column=2)
        btnDecrypt = Button(frame2, text="解密", command=self.decryptFile)
        btnDecrypt.grid(row=1, column=3)

        self.text = Text(window)
        self.text.pack()
        window.mainloop()

    def openFile(self):
        inFileName = askopenfilename()
        inFile = open(inFileName, "r")
        self.fileName.set(inFileName)
        self.fileContext = inFile.read()
        self.text.delete(1.0, END)
        self.text.insert(END, self.fileContext)
        inFile.close()

    def encryptFile(self):
        key = eval(self.key.get())
        caesar = Caesar(key)
        encryptStr = caesar.encrypt(self.fileContext)
        outfileName = asksaveasfilename()
        outFile = open(outfileName, "w")
        outFile.write(encryptStr)
        outFile.close()

    def decryptFile(self):
        key = eval(self.key.get())
        caesar = Caesar(key)
        decryptStr = caesar.decrypt(self.fileContext)
        outfileName = asksaveasfilename()
        outFile = open(outfileName, "w")
        outFile.write(decryptStr)
        outFile.close()

Caesar类

Caesar类提供了一个基本的凯撒密码加密和解密功能,可以与前面介绍的GUI应用程序一起使用。用户只需要输入密钥,就可以对文件内容进行加密和解密操作

  • encrypt(self, Text):实现对输入文本Text的加密。遍历输入文本的每个字符,如果字符在self.biao中出现,则找到该字符在self.biao中的索引位置。然后将该索引加上密钥self.miyao,并对字符集长度取余,得到密文字符在self.biao中的新索引。最后,将新索引对应的字符添加到cipText字符串中,形成最终的密文。返回加密后的密文字符串。
  • decrypt(self, cipText):实现了对输入密文cipText的解密。与encrypt方法类似,但是将索引减去密钥self.miyao,而不是加上。解密时,同样对字符集长度取余,得到明文字符在self.biao中的索引。将明文字符添加到clearText字符串中,形成最终的明文。方法返回解密后的明文字符串。
class Caesar:
    def __init__(self, miyao):
      self.miyao = miyao
      self.biao = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 `-=~!@#$%^&*()_+,./<>?{}|[]\\;:\'\""
    def encrypt(self,Text):
        cipText = ""
        for char in Text:
            if char in self.biao:
                index = self.biao.find(char)
                cipherIndex = (index + self.miyao) % len(self.biao)
                cipText += self.biao[cipherIndex]
        return cipText
    def decrypt(self,cipText):
        clearText = ""
        for char in cipText:
            if char in self.biao:
                index = self.biao.find(char)
                clearIndex = (index - self.miyao) % len(self.biao)
                clearText += self.biao[clearIndex]
        return clearText

调用方法

# 创建Caesar类的实例,密钥为3
caesar = Caesar(3)
# 加密文本"Hello, world!"
encrypted_text = caesar.encrypt("Hello, world!")
print("Encrypted text:", encrypted_text)
# 解密密文
decrypted_text = caesar.decrypt(encrypted_text)
print("Decrypted text:", decrypted_text)

总代码

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
class Caesar:
    def __init__(self, miyao):
      self.miyao = miyao
      self.biao = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 `-=~!@#$%^&*()_+,./<>?{}|[]\\;:\'\""
    def encrypt(self,Text):
        cipText = ""
        for char in Text:
            if char in self.biao:
                index = self.biao.find(char)
                cipherIndex = (index + self.miyao) % len(self.biao)
                cipText += self.biao[cipherIndex]
        return cipText
    def decrypt(self,cipText):
        clearText = ""
        for char in cipText:
            if char in self.biao:
                index = self.biao.find(char)
                clearIndex = (index - self.miyao) % len(self.biao)
                clearText += self.biao[clearIndex]
        return clearText


class FileEncryptWindow():
    def __init__(self):
        window = Tk()

        frame1 = Frame(window)
        frame1.pack()
        labelFileName = Label(frame1, text="文件名:", )
        labelFileName.grid(row=0, column=0)
        self.fileName = StringVar()
        entryFileName = Entry(frame1, width=100, textvariable=self.fileName)
        entryFileName.grid(row=0, column=1)
        btnOpen = Button(frame1, text="打开", command=self.openFile)
        btnOpen.grid(row=0, column=2)

        frame2 = Frame(window)
        frame2.pack()
        labelKey = Label(frame2, text="密钥:", )
        labelKey.grid(row=1, column=0)
        self.key = StringVar()
        entryKey = Entry(frame2, textvariable=self.key)
        self.key.set("3")
        entryKey.grid(row=1, column=1)
        btnEncrypt = Button(frame2, text="加密", command=self.encryptFile)
        btnEncrypt.grid(row=1, column=2)
        btnDecrypt = Button(frame2, text="解密", command=self.decryptFile)
        btnDecrypt.grid(row=1, column=3)

        self.text = Text(window)
        self.text.pack()
        window.mainloop()

    def openFile(self):
        inFileName = askopenfilename()
        inFile = open(inFileName, "r")
        self.fileName.set(inFileName)
        self.fileContext = inFile.read()
        self.text.delete(1.0, END)
        self.text.insert(END, self.fileContext)
        inFile.close()

    def encryptFile(self):
        key = eval(self.key.get())
        caesar = Caesar(key)
        encryptStr = caesar.encrypt(self.fileContext)
        outfileName = asksaveasfilename()
        outFile = open(outfileName, "w")
        outFile.write(encryptStr)
        outFile.close()

    def decryptFile(self):
        key = eval(self.key.get())
        caesar = Caesar(key)
        decryptStr = caesar.decrypt(self.fileContext)
        outfileName = asksaveasfilename()
        outFile = open(outfileName, "w")
        outFile.write(decryptStr)
        outFile.close()


FileEncryptWindow()

点击"打开"按钮,选择要加密或解密的文件。
在密钥输入框中输入密钥值(默认为3)。
点击"加密"或"解密"按钮,输出文件将被保存到用户选择的路径

  • 35
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
如果你想在PyCharm中实现GUI文档加密,可以尝试以下步骤: 1. 安装PyPDF2库,可以使用命令`pip install PyPDF2`来安装。 2. 在你的PyCharm项目中,使用Python的subprocess库调用系统默认的PDF阅读器来打开要加密的PDF文档。 3. 在你的GUI应用程序中,创建一个密码输入框和一个“确认”按钮。 4. 当用户尝试打开PDF文档时,弹出一个提示框,要求用户输入密码。 5. 在用户输入密码后,使用PyPDF2库来加密这个PDF文档。你可以按照以下示例代码来实现: ```python import PyPDF2 # 打开要加密的PDF文档 pdf_file = open('example.pdf', 'rb') # 创建一个PDFReader对象 pdf_reader = PyPDF2.PdfFileReader(pdf_file) # 创建一个PDFWriter对象 pdf_writer = PyPDF2.PdfFileWriter() # 遍历PDF文档的所有页面 for page_num in range(pdf_reader.numPages): pdf_writer.addPage(pdf_reader.getPage(page_num)) # 设置密码 pdf_writer.encrypt('password') # 保存加密后的PDF文档 result_pdf = open('result.pdf', 'wb') pdf_writer.write(result_pdf) # 关闭文件 pdf_file.close() result_pdf.close() ``` 这段代码会创建一个PDFReader对象和一个PDFWriter对象,然后遍历PDF文档的所有页面,并将它们添加到PDFWriter对象中。最后,使用encrypt()方法设置密码并保存加密后的PDF文档。 需要注意的是,这种方法中的密码是明文存储在代码中的,因此并不是非常安全。如果你需要更安全的保护,请考虑使用加密算法对密码进行加密

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鷇韩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值