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_())

python-GUI-pyqt5之文件加密解密工具的更多相关文章

  1. pyDes 实现 Python 版的 DES 对称加密/解密--转

    https://my.oschina.net/leejun2005/blog/586451 手头有个 Java 版的 DES 加密/解密程序,最近想着将其 Python 重构下,方便后续脚本解析,捣鼓 ...

  2. linux环境下给文件加密/解密的方法

      原文地址:linix环境下给文件加密/解密的方法 作者:oracunix 一. 利用 vim/vi 加密:优点:加密后,如果不知道密码,就看不到明文,包括root用户也看不了:缺点:很明显让别人知 ...

  3. 齐博软件(地方门户系统) 文件加密破解工具

    原文:齐博软件(地方门户系统) 文件加密破解工具 本程序为针对"齐博软件地方门户系统5.0官方原版"的破解工具,一个垃圾系统居然弄出这么恶心的加密方式,有个鸟用!以后见一个破一个! ...

  4. 使用jframe编写一个base64加密解密工具

    该工具可以使用exe4j来打包成exe工具(如何打包自己百度) 先上截图功能 运行main方法后,会弹出如下窗口 输入密文 然后点击解密,在点格式化 代码分享 package tools;import ...

  5. Base64加密解密工具类

    使用Apache commons codec类Base64进行加密解密 maven依赖 <dependency> <groupId>commons-codec</grou ...

  6. Java AES加密解密工具 -- GUI 、在线传输文件

    原理 对于任意长度的明文,AES首先对其进行分组,每组的长度为128位.分组之后将分别对每个128位的明文分组进行加密. 对于每个128位长度的明文分组的加密过程如下:     (1)将128位AES ...

  7. DES带IV向量加密解密工具

    链接:http://pan.baidu.com/s/1kVAV80J  密码:sgys 鉴于网上的DES加密解密都是不带IV向量的 我就自制了一个带IV向量的DES加密解密的小工具 © 2016-20 ...

  8. 自己写的AES和RSA加密解密工具

    package com.sdyy.common.utils; import java.security.Key; import java.security.KeyFactory; import jav ...

  9. android 中文件加密 解密 算法实战

    现在项目里面有一个需求,本项目里面下载的视频和文档都不允许通过其他的播放器播放,在培训机构里面这样的需求很多.防止有人交一份钱,把所有的课件就拷给了别人.这样的事情培训机构肯定是不愿意的.现在我项目里 ...

  10. 加密解密工具类(Java,DES)

    一个Java版的DES加密工具类,能够用来进行网络传输数据加密,保存password的时候进行加密. import java.security.Key; import java.security.sp ...

随机推荐

  1. CentOS网络服务操作命令

    CentOS 重启网络服务,输入下面的命令:systemctl retart network.service 或 systemctl restart network.CentOS 启动网络服务,输入下 ...

  2. iOS 12.3 - iOS 13.X 爱思助手越狱教程

    原文链接 本教程使用工具为爱思助手 Mac 版,Windows 电脑可以安装"黑苹果"系统后,在"黑苹果"系统内安装爱思助手再进行操作. 支持设备:iPhone ...

  3. ES6的模块化(export导出)

    ES6 Module把一个文件当作一个模块,每个模块有自己的独立作用域,那如何把每个模块联系起来呢?核心点就是模块的导入(import)与导出(export). 模块化的好处: 防止命名冲突 代码复用 ...

  4. react module.scss文件中弹窗中 keyframes动画不生效,

    以下修改,亲测有效非弹窗内动画写法 .submit_btn{   animation: submit_btn 1.5s infinite;     -webkit-animation: submit_ ...

  5. vue3使用swiper 完整步骤

    注意: 使用之前请确定使用的swiper版本,避免走一些不必要的弯路(笔者踩过来的)本文采用的是vue3.0.swiper^8.1.0. 1.安装依赖 npm install swiper 2.vue ...

  6. heap 算法函数

    这一系列函数是在做 这道题 时发现的 这道题空间卡的很死,是不能用数组存下所有数字进行快排的 后来又尝试用 \(multiset\) 优化空间,发现不行,可能是 \(multiset\) 还有结构性存 ...

  7. Spring Boot 启动时自动执行代码的几种方式

    来源:https://mp.weixin.qq.com/s/xHAYFaNBRys3iokdJmhzHA 前言 java自身的启动时加载方式 Spring启动时加载方式 代码测试 总结 1.前言 目前 ...

  8. 如何避免reblance

    reblance是什么? 什么时候会发生rebalnce? 如何尽量避免这些情况? 若不可避免的要发生reblance?怎么尽量减少影响? reblance是什么? Reblance是Kafka协调者 ...

  9. WSL2与ensp的40故障

    在使用ensp做radius认证的时候看到了Linux平台的freeradius认证服务器,于是使用了Windows平台的sub system: WSL2,按照网上的教程安装,并且安装了docker ...

  10. PHP Redis - zSet(有序集合)

    有序集合与集合一样,string类型元素的集合,不允许重复的成员. 有序集合,每个元素都会关联一个 double 类型的分数.Redis 通过分数为集合的成员进行从小到大的排序 有序集合的成员是唯一的 ...