python-GUI-pyqt5之文件加密解密工具
阅读原文时间:2023年07月09日阅读:3

pyqt5的文件加密解密程序,用到base64,rsa和aes进行混合解密,代码比较杂乱,可自行整理,仅供学习参考之用,如需转载,请联系博主或附上博客链接,下面直接干货。

程序截图如下:

# -*- coding: utf-8 -*-

Form implementation generated from reading ui file 'hellopyqt5.ui'

Created by: PyQt5 UI code generator 5.11.3

WARNING! All changes made in this file will be lost!

-*- coding: utf-8 -*-

coding: utf-8

import os
import sys
import zlib
import time
import random
from os import path
from PIL import Image
from glob import glob
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QFrame
from PyQt5.QtWidgets import QWidget
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread
from PyQt5.QtCore import pyqtSignal
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtGui import QIcon,QColor,QPainter,QFontMetricsF,QDrag
from PyQt5.QtCore import (QByteArray, QDataStream, QIODevice, QMimeData,QPoint, QSize, Qt)
from Crypto.Cipher import AES
import base64
import json
import codecs
import time
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.PublicKey import RSA
from PIL import Image as ImagePIL, ImageFont, ImageDraw
#随机16位AES密钥
AES_SECRET_KEY = ''.join(random.sample('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 16))
#随机16位填充码
IV = ''.join(random.sample('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 16))
class AESCrypt:
def __init__(self):
self.key =AES_SECRET_KEY #只截取16位
self.iv = IV# 16位字符,用来填充缺失内容,可固定值也可随机字符串,具体选择看需求。
self.mode=AES.MODE_CBC
#CBC好像对中文支持不太好
#self.mode=AES.MODE_EBC

def \_\_pad(self, text):  
    """填充方式,加密内容必须为16字节的倍数,若不足则使用self.iv进行填充"""  
    text\_length = len(text)  
    amount\_to\_pad = AES.block\_size - (text\_length % AES.block\_size)  
    if amount\_to\_pad == 0:  
        amount\_to\_pad = AES.block\_size  
    pad = chr(amount\_to\_pad)  
    return text + pad \* amount\_to\_pad

def \_\_unpad(self, text):  
    pad = ord(text\[-1\])  
    return text\[:-pad\]

def encrypt(self, raw):  
    """加密"""  
    raw = self.\_\_pad(raw)  
    cipher = AES.new(str.encode(self.key),self.mode,str.encode(self.iv))  
  #  msg=cipher.encrypt(str.encode(raw))  
    return base64.b64encode(cipher.encrypt(str.encode(raw)))

def decrypt(self, enc):  
    """解密"""  
    enc = base64.b64decode(enc)  
    cipher = AES.new(str.encode(self.key),self.mode,str.encode(self.iv))  
    return self.\_\_unpad(cipher.decrypt(enc).decode("utf-8"))

def change(c):
#返回字母数字的对应的 ASCII 数值
num = ord(c)
#a的ansii为97,z为122,a~z
if num >= 97 and num <= 120:
num = 97 + ((num - 97) + 2)
#chr返回10进制数字对应的ansii值,也可返回16进制
return chr(num)

def dechange(c):
num = ord(c)
if num >= 97 and num <= 122:
num = (num - 97) + 95
#返回字母数字的对应的 ASCII 数值
return chr(num)

#选择文件加密按钮,支持拖动文件
class Button(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
self.setAcceptDrops(True)

droppath=str(23)  
def dragEnterEvent(self, event):  
    global droppath  
    try:  
        #label4显示  
        ui.label\_4.setVisible(True)  
        #避免重复点击,按钮置为不可用  
        ui.pushButton\_3.setEnabled(False)  
        ui.pushButton\_4.setEnabled(False)  
        ui.pushButton.setEnabled(False)  
        ui.pushButton\_2.setEnabled(False)  
        ui.pushButton\_6.setEnabled(False)  
        droppath=event.mimeData().text()  
        droppath=str(droppath.replace(r'file:///',r'')).replace(r'/',r'\\\\')  
        #print(droppath)  
        f=os.path.splitext(droppath)  
        #鼠标放开函数事件  
        event.accept()  
    except Excetion as e:  
        print(e)

# 鼠标放开执行  
def dropEvent(self, evn):  
    try:  
        global timedrop  
        try:  
            filepath2 = droppath.replace(r'/',r'\\\\')  
            print(filepath2)  
            if filepath2 != '':  
                try:  
                    start=time.time()  
                    file = open(filepath2,'rb').read()  
                    file\_len = len(file)  
                    default\_length = 200  
                    # 伪随机数生成器  
                    random\_generator = Random.new().read  
                    # rsa算法生成实例  
                    rsa = RSA.generate(2048, random\_generator)  
                    #公钥加密,也生成文件吧  
                    rsa\_public\_key = rsa.publickey().exportKey()  
                    #公钥加密  
                    rsakey = RSA.importKey(rsa\_public\_key)  
                    cipher = Cipher\_pkcs1\_v1\_5.new(rsakey)  
                    # 密钥key生成  
                    rsa\_private\_key = rsa.exportKey()  
                    keypath = filepath2  
                    f=os.path.splitext(keypath)  
                    newname = f\[0\] + 'secure'  
                    newname = newname+ '.key'  
                    with open(newname, 'wb') as f:  
                        f.write(rsa\_private\_key)  
                    time.sleep(0.1)  
                    #self.rsignal.emit(str(int(10)))  
                    #长度不用分段  
                    if file\_len < default\_length:  
                        stringrsa = base64.b64encode(cipher.encrypt(file))  
                    else:  
                        #需要分段  
                        offset = 0  
                        res = \[\]  
                        count = 0  
                        while file\_len - offset > 0:  
                            if file\_len - offset > default\_length:  
                                res.append(cipher.encrypt(file\[offset:offset+default\_length\]))  
                            else:  
                                res.append(cipher.encrypt(file\[offset:\]))  
                            offset += default\_length  
                            count = count + 1

                        #print('计数分段次数:'+ str(count))  
                        time.sleep(0.1)  
                        #ui.rsignal.emit(str(int(60)))  
                        #stringrsa = ''  
                        stringrsa = b''.join(res)  
                    stringrsa = base64.b64encode(stringrsa)  
                    #ui.rsignal.emit(str(int(90)))  
                    #下面进行AES加密  
                    stringaes = AESCrypt()  
                    stringaes\_comp = stringaes.encrypt(str(stringrsa))  
                    defilepath = filepath2  
                    ft=os.path.splitext(defilepath)  
                    newjiami = ft\[0\] + '-已加密'  
                    newjiami = newjiami+ ft\[1\]  
                    with open(newjiami,'wb') as f:  
                        f.write(stringaes\_comp)  
                        print('加密成功')  
                    time.sleep(0.1)  
                    #ui.rsignal.emit(str(int(100)))  
                    end=time.time()  
                    timedrop=(format(float(end-start),'.2f'))  
                except Exception as e:  
                    print(e)  
            #ui.stop()  
        except Exception as e:  
            print(e)  
        QMessageBox.information(self,"已完成!", "已成功加密文件到原有目录。" + '\\n' +'共耗时:'+str(timedrop)+' '+'秒',QMessageBox.Yes)  
        ui.pushButton\_3.setEnabled(True)  
        ui.pushButton\_4.setEnabled(True)  
        ui.pushButton.setEnabled(True)  
        ui.pushButton\_2.setEnabled(True)

        #label4隐藏  
        ui.label\_4.setVisible(False)  
        #self.pushButton\_4.setVisible(False)  
        ui.pushButton\_6.setEnabled(True)  
    except Exception as e:  
        print(e)

def dragMoveEvent(self,evn):  
    pass  
    #print('鼠标移入')

#可自行增加选择文件加拖动功能

class Button2(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
self.setAcceptDrops(True)

droppath2=str(23)  
def dragEnterEvent(self, event):  
    if 1==1:  
        QMessageBox.information(ui,"提示", "不支持拖拽文件!",QMessageBox.Yes)  
# 鼠标放开执行  
def dropEvent(self, evn):  
    try:  
        pass#ui.label\_6.setText(dropfile)  
    except Exception as e:  
        print(e)

def dragMoveEvent(self,evn):  
    pass  
    #print('鼠标移入')

#可自行增加选择key加拖动功能

class Button3(QPushButton):
def __init__(self, title, parent):
super().__init__(title, parent)
self.setAcceptDrops(True)

#droppath2=str(23)  
def dragEnterEvent(self, event):  
    #global dropkey  
    try:  
        if 1==1:  
            QMessageBox.information(ui,"提示", "不支持拖拽文件!",QMessageBox.Yes)  
        event.accept()

    except Excetion as e:  
        print(e)

# 鼠标放开执行  
def dropEvent(self, evn):  
    try:  
        pass#event.accept()  
    except Exception as e:  
        print(e)

def dragMoveEvent(self,evn):  
    pass  
    #print('鼠标移入')  

#播放音乐类
#openpic类
class Runthreadmusic(QtCore.QThread):
# 通过类成员对象定义信号对象
rsignal = pyqtSignal(str)
def __init__(self):
super(Runthreadmusic, self).__init__()
self.flag = 1

def \_\_del\_\_(self):  
    self.wait()

def stop(self):  
    self.flag=0  
    print('线程退出了')

def run(self):  
    if self.flag==1:  
        try:  
            musicfile=musicpath\[0\].replace(r'/',r'\\\\')  
            audio = MP3(musicfile)  
            musiclen=audio.info.length  
            playsound=pygame.mixer.music.load(musicfile)  
            pygame.mixer.music.play()  
            fenge=("{:.0f}".format(musiclen))  
            fen=("{:.2f}".float(100/float(fenge)))  
            for i in (1,101):  
                self.rsignal.emit(str(float(i)\*float(fen)))  
        except Exception as e:  
            print(e)  

#拖动文件drop类
class Runthreaddrop(QtCore.QThread):
# 通过类成员对象定义信号对象
rsignal = pyqtSignal(str)
def __init__(self):
super(Runthreaddrop, self).__init__()
self.flag = 1

def \_\_del\_\_(self):  
    self.wait()

def stop(self):  
    self.flag=0  
    print('线程退出了')

def run(self):  
    if self.flag==1:  
        try:  
            print('进入线程')  
            path=str(droppath)  
            if path!= '':  
                try:  
                    im = Image.open(path)  # 打开图片  
                    imBytes = im.tobytes()  # 把图片转换成bytes流  
                    imBytes = zlib.compress(imBytes, 9)  # 对图像字节串进行压缩,第二个参数是压缩率有-1,0-9.  
                    if im.mode == 'RGBA':  
                        im2 = Image.frombytes('RGBA',im.size, zlib.decompress(imBytes))  # 压缩成新的图片  
                    else:  
                        im2 = Image.frombytes('RGB',im.size, zlib.decompress(imBytes))  
                    f=os.path.splitext(path)  
                    newname=f\[0\] + '-已压缩'  
                    newname=newname+f\[1\]  
                    im2.save(newname)  
                    self.rsignal.emit(str(int(100)))  
                except Exception as e:  
                    print(e)  
            self.stop()  
        except Exception as e:  
            print(e)

#解密类
class Runthreadjiemi(QtCore.QThread):
# 通过类成员对象定义信号对象
rsignal = pyqtSignal(str)
def __init__(self):
super(Runthreadjiemi, self).__init__()
self.flag = 1

def \_\_del\_\_(self):  
    self.wait()

def stop(self):  
    self.flag=0  
    print('线程退出了')  
def run(self):  
    if self.flag==1:  
        global usedtime4  
        try:  
            try:  
                start=time.time()  
                watebytes = open(jiemifile\[0\],'rb').read()  
                #第一步先AES解密  
                deaes = AESCrypt()  
                destring = watebytes.decode()  
                watebytes = deaes.decrypt(destring)  
                time.sleep(0.1)  
                #补等号  
                missing\_padding = len(watebytes) % 4  
                #print(missing\_padding)  
                if missing\_padding != 0:  
                    #print('需要补等号')  
                    #string\_new = bytes(file, encoding='utf-8')  
                    watebytes = str(watebytes).replace("b'","").replace("'","")  
                    watebytes += '=' \* (4 - missing\_padding)  
                self.rsignal.emit(str(int(33)))  
                #第二步base64解密  
                try:  
                    watebytes =bytes(watebytes,encoding='utf-8')  
                    stringbyte = base64.b64decode(watebytes)#.encode('utf-8'))  
                    #print(stringbyte)  
                    file2 = stringbyte  
                    length2 = len(file2)  
                    #print(length2)  
                    default\_length2 = 256  
                    rsa\_private\_key=open(jiemikey\[0\],'rb').read()  
                    rsakey2=RSA.importKey(rsa\_private\_key)  
                    self.rsignal.emit(str(int(66)))  
                except Exception as e:  
                    if e == 'Incorrect padding':  
                        QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)  
                    else:  
                        QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)

                time.sleep(0.1)  
                #第三部RSA私钥解密  
                cipher2 = Cipher\_pkcs1\_v1\_5.new(rsakey2)  
                #长度不用分段  
                if length2 < default\_length2:  
                    string\_write = b''.join(cipher2.decrypt(file2,None))  
                else:  
                    #需要分段  
                    offset2 = 0  
                    res2 = \[\]  
                    while length2 - offset2 > 0:  
                        if length2 - offset2 > default\_length2:  
                            res2.append(cipher2.decrypt(file2\[offset2:offset2+default\_length2\],None))  
                        else:  
                            res2.append(cipher2.decrypt(file2\[offset2:\],None))  
                        offset2 += default\_length2  
                    self.rsignal.emit(str(int(80)))  
                    string\_write = b''.join(res2)  
                jiemipath = jiemifile\[0\]  
                f=os.path.splitext(jiemipath)  
                newname=f\[0\] + '-已解密'  
                newname=newname+f\[1\]  
                with open(newname,'wb') as f:  
                    f.write(string\_write)  
                    print('解密成功')  
                #信号传给进度条100%了  
                self.rsignal.emit(str(int(100)))  
            except Exception as e:  
                print(e)  
            end=time.time()  
            usedtime4=(format(float(end-start),'.2f'))  
            #print("共耗时: %.02f 秒" %(float(usedtime4)))  
            self.stop()  
        except UnicodeError:  
            QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)  
        except UnicodeEncodeError:  
            QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)  
        except UnicodeDecodeError:  
            QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)  
        except UnicodeTranslateError:  
            QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)  
        except IOError:  
            QMessageBox.information(ui,"错误", "不能写入文件,请选择正确的加密文件和key密钥!",QMessageBox.Yes)  
        except BaseException:  
            QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)  
        except Exception as e:  
            print(e)  
            if e == "'utf-8' codec can't decode byte 0xff in position 0: invalid start byte":  
                QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)  
            else:  
                QMessageBox.information(ui,"错误", "请选择正确的加密文件和key密钥!",QMessageBox.Yes)  

#opendic类
class Runthreaddic(QtCore.QThread):
# 通过类成员对象定义信号对象
rsignal = pyqtSignal(str)
def __init__(self):
super(Runthreaddic, self).__init__()
self.flag = 1

def \_\_del\_\_(self):  
    self.wait()

def stop(self):  
    self.flag=0  
    print('线程退出了')

def run(self):  
    if self.flag==1:  
        global usedtime2  
        try:  
            path=dic.replace(r'/',r'\\\\')  
            # glob.glob()用来进行模糊查询,增加参数recursive=True后可以使用\*\*/来匹配所有子目录  
            files = glob( path + "\*\*/\*.JPG", recursive=True) + glob(path + "\*\*/\*.bmp", recursive=True) + glob(path + "\*\*/\*.png", recursive=True)  
            total = len(files) #总文件数  
            cur = 1 #当前文件序号  
            i=1  
            start=time.time()  
            for infile in files:  
                try:  
                    #f, ext = os.path.splitext(infile) # 分离文件名和后缀  
                    #print("进度:" + str(cur) + "/" + str(total) + "   " + infile)  
                    img = Image.open(infile) # 打开图片文件  
                    if img.width>5:  
                        width=img.width  
                        height=img.height  
                        size=(width\*bs,height\*bs)  
                        img.thumbnail(size, Image.ANTIALIAS) # 使用抗锯齿模式生成缩略图(压缩图片)  
                        f=os.path.splitext(infile)  
                        newname=f\[0\] + '-已压缩'  
                        newname=newname+f\[1\]  
                        #不指定编码格式  
                        img.save(newname) # , "JPEG"infile保存成与原文件名一致的文件,会自动覆盖源文件  
                        bfb=int(100/total)  
                        if i==total:  
                            self.rsignal.emit(str(int(100)))  
                            self.quit()  
                        else:  
                            self.rsignal.emit(str(bfb\*i))  
                        i=i+1  
                    else:  
                        print(infile + "宽度小于1200px,无需处理,已忽略")  
                    cur = cur + 1  
                except Exception as e:  
                    print(e)  
            end=time.time()  
            usedtime2=(format(float(end-start),'.2f'))  
            #print("共耗时: %.02f 秒" %(float(usedtime2)))  
            self.stop()  
        except Exception as e:  
            print(e)

#加密类
class Runthreadjiami(QtCore.QThread):
# 通过类成员对象定义信号对象
rsignal = pyqtSignal(str)
def __init__(self):
super(Runthreadjiami, self).__init__()
self.flag = 1

def \_\_del\_\_(self):  
    self.wait()

def stop(self):  
    self.flag=0  
    print('线程退出了')

def run(self):  
    if self.flag==1:  
        global usedtime3

        try:  
            filepath2 = filepath.replace(r'/',r'\\\\')  
            if filepath2 != '':  
                try:  
                    start=time.time()  
                    file = open(filepath2,'rb').read()  
                    file\_len = len(file)  
                    default\_length = 200  
                    # 伪随机数生成器  
                    random\_generator = Random.new().read  
                    # rsa算法生成实例  
                    rsa = RSA.generate(2048, random\_generator)  
                    #公钥加密,也生成文件吧  
                    rsa\_public\_key = rsa.publickey().exportKey()  
                    #print(rsa\_public\_key)  
                    #with open('01.pub', 'wb') as f:  
                    #    f.write(rsa\_public\_key)  
                    #公钥加密  
                    rsakey = RSA.importKey(rsa\_public\_key)  
                    cipher = Cipher\_pkcs1\_v1\_5.new(rsakey)  
                    # 密钥key生成  
                    rsa\_private\_key = rsa.exportKey()  
                    #print(rsa\_private\_key)  
                    #f=os.path.splitext(path)  
                    #newname=f\[0\] + '-已压缩'  
                    #newname=newname+ '.key'  
                    keypath = filepath2  
                    f=os.path.splitext(keypath)  
                    newname = f\[0\] + 'secure'  
                    newname = newname+ '.key'  
                    with open(newname, 'wb') as f:  
                        f.write(rsa\_private\_key)  
                    time.sleep(0.1)  
                    self.rsignal.emit(str(int(20)))  
                    #长度不用分段  
                    if file\_len < default\_length:  
                        stringrsa = base64.b64encode(cipher.encrypt(file))  
                    else:  
                        #需要分段  
                        offset = 0  
                        res = \[\]  
                        count = 0  
                        while file\_len - offset > 0:  
                            if file\_len - offset > default\_length:  
                                res.append(cipher.encrypt(file\[offset:offset+default\_length\]))  
                            else:  
                                res.append(cipher.encrypt(file\[offset:\]))  
                            offset += default\_length  
                            count = count + 1  
                        #print('计数分段次数:'+ str(count))  
                        time.sleep(0.1)  
                        self.rsignal.emit(str(int(60)))  
                        #stringrsa = ''  
                        stringrsa = b''.join(res)  
                    stringrsa = base64.b64encode(stringrsa)  
                    self.rsignal.emit(str(int(80)))  
                    #下面进行AES加密  
                    stringaes = AESCrypt()  
                    stringaes\_comp = stringaes.encrypt(str(stringrsa))  
                    defilepath = filepath2  
                    ft=os.path.splitext(defilepath)  
                    newjiami = ft\[0\] + '-已加密'  
                    newjiami = newjiami+ ft\[1\]  
                    with open(newjiami,'wb') as f:  
                        f.write(stringaes\_comp)  
                        print('加密成功')  
                    time.sleep(0.1)  
                    self.rsignal.emit(str(int(100)))  
                    end=time.time()  
                    usedtime3=(format(float(end-start),'.2f'))  
                except Exception as e:  
                    print(e)  
            self.stop()  
        except Exception as e:  
            print(e)

#opendicno类
class Runthreaddicno(QtCore.QThread):
# 通过类成员对象定义信号对象
rsignal = pyqtSignal(str)
#signal2 = pyqtSignal(str)
def __init__(self):
super(Runthreaddicno, self).__init__()
self.flag = 1

def \_\_del\_\_(self):  
    self.wait()

def stop(self):  
    self.flag=0  
    #self.msgbox1=msgbox()  
    #self.newmsg=msgbox1.msg()  
    print('线程退出了')

def run(self):  
    global usedtime  
    if self.flag==1:  
        try:  
            path=dic.replace(r'/',r'\\\\')  
            if dic != '':  
                path=dic.replace(r'/',r'\\\\')  
                # glob.glob()用来进行模糊查询,增加参数recursive=True后可以使用\*\*/来匹配所有子目录  
                files = glob( path + "\*\*/\*.JPG", recursive=True) + glob(path + "\*\*/\*.bmp", recursive=True) + glob(path + "\*\*/\*.png", recursive=True)  
                total = len(files) #总文件数  
                print(total)  
                cur = 1 #当前文件序号  
                i=1  
                print(files)  
                start=time.time()  
                for infile in files:  
                    try:  
                        #print("进度:" + str(cur) + "/" + str(total) + "   " + infile)  
                        im = Image.open(infile) # 打开图片文件  
                        if im.width>5:  
                            imBytes = im.tobytes()  
                            imBytes = zlib.compress(imBytes, 9)  
                            if im.mode == 'RGBA':  
                                im2 = Image.frombytes('RGBA', im.size, zlib.decompress(imBytes))  # 压缩成新的图片  
                            else:  
                                im2 = Image.frombytes('RGB', im.size, zlib.decompress(imBytes))  
                            #改名------------------------  
                            f=os.path.splitext(infile)  
                            newname=f\[0\] + '-已压缩'  
                            newname=newname+f\[1\]  
                            #改名------------------------  
                            im2.save(newname) # 保存成与原文件名一致的文件,会自动覆盖源文件  
                            bfb=int(100/total)  
                            if i==total:  
                                self.rsignal.emit(str(int(100)))  
                                #os.\_exit(0)退出整个程序,不好  
                                self.quit()  
                            else:  
                                self.rsignal.emit(str(bfb\*i))  
                            i=i+1  
                        else:  
                            print(infile + "宽度小于1200px,无需处理,已忽略")  
                        cur = cur + 1  
                    except Exception as e:  
                        print(e)  
                end=time.time()  
                usedtime=(format(float(end-start),'.2f'))  
                #print("共耗时: %.02f 秒" %(float(usedtime)))  
            self.stop()  
        except Exception as e:  
            print(e)

class Ui_Form(QWidget): # QMainWindow QWidget

def \_\_init\_\_(self):  
    super(QWidget,self).\_\_init\_\_() #QtWidgets.QMainWindow  
    self.setupUi(self)  
    self.retranslateUi(self)  
    # 鼠标拖入事件  
def setupUi(self, Form):  
    Form.setObjectName("Form")  
    Form.resize(368, 290)  
    Form.setFixedSize(368, 260)  
    Form.setWindowTitle('文件加密解密')  
    Form.setWindowIcon(QIcon(':/1.png'))

    self.tabWidget = QtWidgets.QTabWidget(Form)  
    self.tabWidget.setGeometry(QtCore.QRect(10, 10, 351, 271))  
    self.tabWidget.setObjectName("tabWidget")  
    self.tab = QtWidgets.QWidget()  
    #指定显示特定页面  
    #self.tab.setCurrentIndex(0)  
    self.tab.setObjectName("tab")  
    self.pushButton\_4 = QtWidgets.QPushButton(self.tab)  
    self.pushButton\_4.setGeometry(QtCore.QRect(100, 120, 141, 41))  
    self.pushButton\_4.setObjectName("pushButton\_4")  
    self.pushButton\_4.clicked.connect(self.opendicno)  
    self.pushButton\_4.setVisible(False)  
    #加密文件  
    self.pushButton\_3 = Button("pushButton\_3", self.tab)  
    #self.pushButton\_3 = QtWidgets.QPushButton(self.tab)  
    self.pushButton\_3.setGeometry(QtCore.QRect(120, 110, 101, 41))  
    self.pushButton\_3.setObjectName("pushButton\_3")  
    self.pushButton\_3.clicked.connect(self.jiami)  
    self.label = QtWidgets.QLabel(self.tab)  
    self.label.setGeometry(QtCore.QRect(20, 0, 281, 81))  
    self.label.setTextFormat(QtCore.Qt.AutoText)  
    self.label.setWordWrap(True)  
    self.label.setObjectName("label")  
    #进度条1  
    self.progressBar = QtWidgets.QProgressBar(self.tab)  
    self.progressBar.setGeometry(QtCore.QRect(90, 190, 171, 26))  
    self.progressBar.setObjectName("progressBar")  
    self.progressBar.setProperty("value", 0)  
    self.progressBar.setStyleSheet("QProgressBar{border:0px solid #00A0E6;"  
                                   "height:50;"  
                                   "background:#191C21;"  
                                   "text-align:right;"  
                                   "color:white;"  
                                   #"color:rgb(245,220,0);"  
                                   "border-radius:2px;}"

                                   "QProgressBar::chunk{"  
                                   #"border-radius:5px;"  
                                   #"border:1px solid black;"rgb(167,210,102) rgb(245,220,0)  
                                   "background-color:rgb(150,196,64);"  
                                   "width:1px;margin:0.5px;}"  
                                   )  
    #隐藏进度条  
    self.progressBar.setVisible(False)

    self.tabWidget.addTab(self.tab, "")  
    self.tab\_2 = QtWidgets.QWidget()  
    self.tab\_2.setObjectName("tab\_2")  
    #self.tab\_2.setStyleSheet('background-color:#FAEBD7;')  
    #隐藏的Qlineedit  
    self.lineEdit = QtWidgets.QLineEdit(self.tab)  
    self.lineEdit.setGeometry(QtCore.QRect(0, 10, 351, 241))  
    self.lineEdit.setObjectName("lineEdit")  
    self.lineEdit.setVisible(False)  
    #有损压缩选择文件按钮  
    self.pushButton = Button2("pushButton", self.tab\_2)  
    #self.pushButton = QtWidgets.QPushButton(self.tab\_2)  
    self.pushButton.setGeometry(QtCore.QRect(120, 70, 101, 41))  
    self.pushButton.setCheckable(False)  
    self.pushButton.setObjectName("pushButton")  
    #选择key支持拖动  
    self.pushButton.clicked.connect(self.openfile)  
    self.pushButton\_2 = Button3("pushButton\_2", self.tab\_2)  
    #self.pushButton\_2 = QtWidgets.QPushButton(self.tab\_2)  
    self.pushButton\_2.setGeometry(QtCore.QRect(120, 120, 101, 41))  
    self.pushButton\_2.setCheckable(False)  
    self.pushButton\_2.setObjectName("pushButton\_2")  
    #有损压缩打开文件夹  
    self.pushButton\_2.clicked.connect(self.opendic)  
    #解密文件按钮  
    #self.pushButton\_6 = Button3("pushButton\_6", self.tab\_2)  
    self.pushButton\_6 = QtWidgets.QPushButton(self.tab\_2)  
    self.pushButton\_6.setGeometry(QtCore.QRect(110, 170, 121, 41))  
    self.pushButton\_6.setCheckable(False)  
    self.pushButton\_6.setObjectName("pushButton\_6")  
    self.pushButton\_6.clicked.connect(self.jiemi)  
    ######停止线程  
    self.pushButton\_7 = QtWidgets.QPushButton(self.tab\_2)  
    self.pushButton\_7.setGeometry(QtCore.QRect(250, 120, 91, 41))  
    self.pushButton\_7.setCheckable(False)  
    self.pushButton\_7.setObjectName("pushButton\_7")  
    self.pushButton\_7.clicked.connect(self.stopjiemi)  
    self.pushButton\_7.setVisible(False)  
    self.pushButton\_7.setStyleSheet("color:red;""background:#191C21;""font:微软雅黑;")  
    self.tabWidget.addTab(self.tab\_2, "")  
    #label4  
    self.label\_4 = QtWidgets.QLabel(self.tab)  
    self.label\_4.setGeometry(QtCore.QRect(20, 170, 161, 16))  
    font4 = QtGui.QFont()  
    font4.setFamily("微软雅黑")  
    font4.setPointSize(10)  
    self.label\_4.setFont(font4)  
    self.label\_4.setObjectName("label\_4")  
    self.label\_4.setVisible(False)  
    #label5  
    self.label\_5 = QtWidgets.QLabel(self.tab\_2)  
    self.label\_5.setGeometry(QtCore.QRect(20, 160, 151, 16))  
    font5 = QtGui.QFont()  
    font5.setFamily("微软雅黑")  
    font5.setPointSize(10)  
    self.label\_5.setFont(font5)  
    self.label\_5.setObjectName("label\_5")  
    self.label\_5.setVisible(False)  
    #label6,7  
    self.label\_6 = QtWidgets.QLabel(self.tab\_2)  
    self.label\_6.setGeometry(QtCore.QRect(0, 50, 341, 16))  
    self.label\_6.setObjectName("label\_6")  
    self.label\_6.setVisible(True)  
    self.label\_7 = QtWidgets.QLabel(self.tab\_2)  
    self.label\_7.setGeometry(QtCore.QRect(0, 110, 341, 16))  
    self.label\_7.setObjectName("label\_7")  
    self.label\_7.setVisible(True)  
    #label红色字  
    font8 = QtGui.QFont()  
    font8.setFamily("微软雅黑")  
    font8.setPointSize(10)  
    self.label\_8 = QtWidgets.QLabel(self.tab\_2)  
    self.label\_8.setGeometry(QtCore.QRect(0, 80, 331, 20))  
    self.label\_8.setObjectName("label\_8")  
    self.label\_8.setFont(font8)  
    self.label\_8.setStyleSheet("color:red;")  
    self.label\_8.setVisible(False)  
    #进度条2  
    self.progressBar\_2 = QtWidgets.QProgressBar(self.tab\_2)  
    self.progressBar\_2.setGeometry(QtCore.QRect(100, 210, 171, 26))  
    self.progressBar\_2.setObjectName("progressBar\_2")  
    self.progressBar\_2.setProperty("value", 0)  
    self.progressBar\_2.setStyleSheet("QProgressBar{border:0px solid #00A0E6;"  
                                    "height:50;"  
                                    "background:#191C21;"  
                                    "text-align:right;"  
                                    "color:white;"  
                                    #"color:rgb(245,220,0);"  
                                    "border-radius:2px;}"  
                                    "QProgressBar::chunk{"  
                                    #"border-radius:5px;"  
                                    #"border:1px solid black;"rgb(167,210,102) rgb(245,220,0)  
                                    "background-color:rgb(150,196,64);"  
                                    "width:1px;margin:0.5px;}"  
                                     )  
    #隐藏进度条2  
    self.progressBar\_2.setVisible(False)  
    self.label\_2 = QtWidgets.QLabel(self.tab\_2)  
    self.label\_2.setGeometry(QtCore.QRect(20, 10, 281, 51))  
    self.label\_2.setTextFormat(QtCore.Qt.AutoText)  
    self.label\_2.setWordWrap(True)  
    self.label\_2.setObjectName("label\_2")  
    self.tabWidget.addTab(self.tab\_2, "")  
    self.tabWidget.setCurrentIndex(0)  
    self.retranslateUi(Form)  
    #原来是你  
    QtCore.QMetaObject.connectSlotsByName(Form)

def jiemi(self):  
    try:  
        if jiemifile\[0\] !='' and jiemikey\[0\] !='':  
            self.thread = Runthreadjiemi()  
            self.thread.rsignal.connect(self.call\_backlogjiemi)  # 进程连接回传到GUI的事件  
            #子进程开始前让进度条可见  
            self.progressBar\_2.setVisible(True)  
            #label5显示  
            self.label\_5.setVisible(True)  
            self.label\_8.setVisible(True)  
            self.thread.start()  
            #避免重复点击,按钮置为不可用  
            self.pushButton\_3.setEnabled(False)  
            self.pushButton\_4.setEnabled(False)  
            self.pushButton.setEnabled(False)  
            self.pushButton\_2.setEnabled(False)  
            self.pushButton\_6.setEnabled(False)  
            self.pushButton\_7.setVisible(True)  
        else:  
            QMessageBox.information(self,"错误", "请先选择好加密文件和key后再点击解密文件!",QMessageBox.Yes)  
    except Exception as e:  
        pass  
def call\_backlogjiemi(self, msg):  
    self.progressBar\_2.setValue(int(msg))  # 将线程的参数传入进度条  
    #结束了顺带传给消息框  
    try:  
        if int(msg)==100:  
            time.sleep(0.1)  
            QMessageBox.information(self,"已完成!", "已成功解密文件到原有目录。" + '\\n' +'共耗时:'+str(usedtime4)+' '+'秒',QMessageBox.Yes)  
            #QMessageBox.information(self,"已完成!", "已成功压缩图片到原有目录",QMessageBox.Yes)  
            #子线程结束后执行以下  
            #设计进度条隐藏  
            self.progressBar\_2.setValue(0)  
            self.progressBar\_2.setVisible(False)  
            #设置按钮可用  
            self.pushButton\_3.setEnabled(True)  
            self.pushButton\_4.setEnabled(True)  
            self.pushButton.setEnabled(True)  
            self.pushButton\_2.setEnabled(True)  
            #label5隐藏  
            self.label\_5.setVisible(False)  
            self.pushButton\_6.setEnabled(True)  
            jiemifile = ''  
            jiemikey = ''  
            self.label\_6.setText("")  
            self.label\_7.setText("")  
            self.label\_8.setVisible(False)  
            self.pushButton\_7.setVisible(False)  
    except Exception as e:  
        print(e)  
def stopjiemi(self):  
    try:  
        reply = QMessageBox.information(self,"询问", "确定要停止解密吗?",QMessageBox.Yes | QMessageBox.No)  
        if reply == QMessageBox.Yes:  
            #QMessageBox.information(self,"已完成!", "已成功压缩图片到原有目录",QMessageBox.Yes)  
            #子线程结束后执行以下  
            #设计进度条隐藏  
            self.progressBar\_2.setValue(0)  
            self.progressBar\_2.setVisible(False)  
            #设置按钮可用  
            self.pushButton\_3.setEnabled(True)  
            self.pushButton\_4.setEnabled(True)  
            self.pushButton.setEnabled(True)  
            self.pushButton\_2.setEnabled(True)  
            #label5隐藏  
            self.label\_5.setVisible(False)  
            self.pushButton\_6.setEnabled(True)  
            jiemifile = ''  
            jiemikey = ''  
            self.label\_6.setText("")  
            self.label\_7.setText("")  
            self.label\_8.setVisible(False)  
            self.pushButton\_7.setVisible(False)  
        else:  
            pass  
    except Exception as e:  
        print(e)  
def openfile(self):  
    try:  
        global jiemifile  
        jiemifile = QFileDialog.getOpenFileName(self,"选择文件","./","All Files (\*.\*)")  
        self.label\_6.setText(jiemifile\[0\])  
    except Exception as e:  
        print(e)

def opendic(self):  
    try:  
        global jiemikey  
        jiemikey = QFileDialog.getOpenFileName(self,"选择文件","./","All Files (\*.key)")  
        self.label\_7.setText(jiemikey\[0\])  
    except Exception as e:  
          print(e)

def call\_backlogdic(self, msg):  
    self.progressBar\_2.setValue(int(msg))  # 将线程的参数传入进度条  
    #结束了顺带传给消息框  
    try:  
        if int(msg)==100:  
            QMessageBox.information(self,"已完成!", "已成功解密文件到原有目录。" + '\\n' +'共耗时:'+str(usedtime2)+' '+'秒',QMessageBox.Yes)  
            #QMessageBox.information(self,"已完成!", "已成功压缩图片到原有目录",QMessageBox.Yes)  
            #子线程结束后执行以下  
            #设计进度条隐藏  
            self.progressBar\_2.setValue(0)  
            self.progressBar\_2.setVisible(False)  
            #设置按钮可用  
            self.pushButton\_3.setEnabled(True)  
            self.pushButton\_4.setEnabled(True)  
            self.pushButton.setEnabled(True)  
            self.pushButton\_2.setEnabled(True)

            #label5隐藏  
            self.label\_5.setVisible(False)  
    except Exception as e:  
        print(e)

def jiami(self):  
    global filepath  
    fileselect = QFileDialog.getOpenFileName(self,"选择文件","./","All Files (\*.\*)")  
    filepath = fileselect\[0\]  
    print(filepath)  
    if filepath!='':  
        self.thread = Runthreadjiami()  
        self.thread.rsignal.connect(self.call\_backlogjiami)  # 进程连接回传到GUI的事件  
        #子进程开始前让进度条可见  
        self.progressBar.setVisible(True)  
        #label4显示  
        self.label\_4.setVisible(True)  
        self.thread.start()  
        #避免重复点击,按钮置为不可用  
        self.pushButton\_3.setEnabled(False)  
        self.pushButton\_4.setEnabled(False)  
        self.pushButton.setEnabled(False)  
        self.pushButton\_2.setEnabled(False)  
        self.pushButton\_6.setEnabled(False)

def call\_backlogjiami(self, msg):  
    self.progressBar.setValue(int(msg))  # 将线程的参数传入进度条  
    #结束了顺带传给消息框  
    try:  
        if int(msg)==100:  
            QMessageBox.information(self,"已完成!", "已成功加密文件到原有目录。" + '\\n' +'共耗时:'+str(usedtime3)+' '+'秒',QMessageBox.Yes)  
            #QMessageBox.information(self,"已完成!", "已成功压缩图片到原有目录",QMessageBox.Yes)  
            #子线程结束后执行以下  
            #设计进度条隐藏  
            self.progressBar.setValue(0)  
            self.progressBar.setVisible(False)  
            #设置按钮可用  
            self.pushButton\_3.setEnabled(True)  
            self.pushButton\_4.setEnabled(True)  
            self.pushButton.setEnabled(True)  
            self.pushButton\_2.setEnabled(True)

            #label4隐藏  
            self.label\_4.setVisible(False)  
            #self.pushButton\_4.setVisible(False)  
            self.pushButton\_6.setEnabled(True)  
    except Exception as e:  
        print(e)

def opendicno(self):  
    global dic  
    dic = QFileDialog.getExistingDirectory(self,"选择文件夹", "./")  
    if dic!='':  
        self.thread = Runthreaddicno()  
        self.thread.rsignal.connect(self.call\_backlogdicno)  # 进程连接回传到GUI的事件  
        #子进程开始前让进度条可见  
        self.progressBar.setVisible(True)  
        #label4显示  
        self.label\_4.setVisible(True)  
        self.thread.start()  
        self.pushButton\_3.setEnabled(False)  
        self.pushButton\_4.setEnabled(False)  
        self.pushButton.setEnabled(False)  
        self.pushButton\_2.setEnabled(False)  
        self.radioButton.setEnabled(False)  
        self.radioButton\_2.setEnabled(False)  
        self.radioButton\_3.setEnabled(False)  
        self.radioButton\_4.setEnabled(False)

def call\_backlogdicno(self, msg):  
    self.progressBar.setValue(int(msg))  # 将线程的参数传入进度条  
    #结束了顺带传给消息框  
    try:  
        if int(msg)==100:  
            #usedtime  
            QMessageBox.information(self,"已完成!", "已成功加密文件到原有目录。" + '\\n' +'共耗时:'+str(usedtime)+' '+'秒',QMessageBox.Yes)  
            #子线程结束后执行以下  
            #设计进度条隐藏  
            self.progressBar.setValue(0)  
            self.progressBar.setVisible(False)  
            #设置按钮可用  
            self.pushButton\_3.setEnabled(True)  
            self.pushButton\_4.setEnabled(True)  
            self.pushButton.setEnabled(True)  
            self.pushButton\_2.setEnabled(True)  
            self.radioButton.setEnabled(True)  
            self.radioButton\_2.setEnabled(True)  
            self.radioButton\_3.setEnabled(True)  
            self.radioButton\_4.setEnabled(True)  
            #label4隐藏  
            self.label\_4.setVisible(False)  
    except Exception as e:  
        print(e)

def retranslateUi(self, Form):  
    \_translate = QtCore.QCoreApplication.translate  
    Form.setWindowTitle(\_translate("Form", "文件加密解密"))  
    #self.pushButton\_5.setText(\_translate("Form", "播放歌曲"))  
    self.pushButton\_4.setText(\_translate("Form", "选择文件夹"))  
    self.pushButton\_3.setText(\_translate("Form", "选择文件"))  
    self.label.setText(\_translate("Form", "注:本程序采用AES+RSA等算法加密。请保存好加密所生成的key文件,丢失后文件不可恢复!本程序仅供学习使用,若造成任何文件损坏或遗失,本人概不负责。可直接拖拽至按钮加密文件。"))  
    self.label\_2.setText(\_translate("Form", "注:请先选择文件和对应的key来解密文件。"))  
    self.label\_4.setText(\_translate("Form", "正在加密,请勿关闭程序:"))  
    self.label\_5.setText(\_translate("Form", "正在解密,请勿关闭程序"))  
    self.label\_6.setText(\_translate("Form", ""))  
    self.label\_7.setText(\_translate("Form", ""))  
    self.label\_8.setText(\_translate("Form", "如果进度始终未动,请确保选择了正确的加密文件和key。"))  
    self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), \_translate("Form", "加密文件"))  
    self.pushButton.setText(\_translate("Form", "选择文件"))  
    self.pushButton\_2.setText(\_translate("Form", "选择key"))  
    self.pushButton\_6.setText(\_translate("Form", "解密文件"))  
    self.pushButton\_7.setText(\_translate("Form", "点击停止解密"))  
    self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab\_2), \_translate("Form", "解密文件")) 

if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QMainWindow()
ui = Ui_Form()
ui.setupUi(ui)
Form.show()
sys.exit(app.exec_())

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章