簡體   English   中英

使用 wxpython GUI 加密文件

[英]Encrypt a file with wxpython GUI

我想在 Python 中使用cryptography加密文件。

我正在使用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()

問題是這段代碼:

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

當您甚至沒有顯示對話框時,您就在詢問路徑。 這將導致一個空字符串。

您需要首先顯示模態對話框,然后在用戶驗證文件時獲取路徑:

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

請注意,此構造不是好的做法,並且會阻止您調試可能發生的任何錯誤:

   except Exception as e:
        return False

至少如果發生了不好的事情,打印異常(或使用 wx 對話框將其顯示給用戶)

   except Exception as e:
        print("something bad happened {}".format(e))
        return False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM