使用wxpython GUI加密文件

问题描述 投票:0回答:1

我想用Python中的cryptography加密文件,我知道通常如何做,但是使用GUI我不知道如何做。

我正在使用wx模块,它是一个GUI库,我的应用程序是这样的:如果用户单击Encrypt a File按钮,则该应用程序将打开文件浏览器,并且他能够选择他想要的文件加密。当他单击文件并将其打开时,我的功能将对其进行加密。

但是它不起作用,它只是什么也不做,我没有收到任何错误,并且看起来似乎很好,但是没有。

任何建议?

import wx
import os
import random
import ctypes
from cryptography.fernet import Fernet

desktop = os.path.expanduser('~/Desktop')
fileKey = str(random.SystemRandom().randint(100, 1000)) + 'key.txt'

class myFrame(wx.Frame):
    def __init__(self):
        super().__init__(parent=None, title='Hello!', size=(600, 400), style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)
        panel = wx.Panel(self)
        self.text_ctrl = wx.TextCtrl(panel, pos=(5, 5)) # Edit box
        EncryptButton = wx.Button(panel, label='Encrypt a File', pos=(475, 295), size=(100, 55)).Bind(wx.EVT_BUTTON, self.onOpen) # Encrypt Button
        self.Show() # Show Window

    def onOpen(self, event):
        fileFormat = 'All Files (*.*) | *.*'
        dialog = wx.FileDialog(self, 'Choose File', wildcard=fileFormat, style=wx.FD_OPEN ^ wx.FD_FILE_MUST_EXIST)
        path = dialog.GetPath()
        if dialog.ShowModal() == wx.ID_OK:
            try:
                key = Fernet.generate_key()
                tokenEnc = Fernet(key)
                with open(path, 'rb+') as fobj:
                    plainText = fobj.read()
                    cipherText = tokenEnc.encrypt(plainText)
                    fobj.seek(0)
                    fobj.truncate()
                    fobj.write(cipherText)
                    ctypes.windll.user32.MessageBoxW(0, 'We have Encrypted the File, also, We have created a file with the key in your Desktop.', 'Performed Successfully', 1)
                    with open(os.path.join(desktop, fileKey), 'wb') as keyFile:
                        keyFile.write(key)
            except Exception as e:
                return False

if __name__ == '__main__':
    app = wx.App()
    frame = myFrame()
    app.MainLoop()
python wxpython
1个回答
1
投票

问题是此代码:

    path = dialog.GetPath()
    if dialog.ShowModal() == wx.ID_OK:

您甚至没有显示对话框时就在询问路径。结果为空字符串。

您首先需要显示模式对话框,如果用户验证了文件,则需要获取路径:

    if dialog.ShowModal() == wx.ID_OK:
        path = dialog.GetPath()

请注意,此构造不是一种好习惯,它会阻止您调试any可能发生的错误:

   except Exception as e:
        return False

至少在发生不良情况时,打印异常(或使用wx对话框将其显示给用户)

   except Exception as e:
        print("something bad happened {}".format(e))
        return False
© www.soinside.com 2019 - 2024. All rights reserved.