python 常见文件的加密与解密
一、代码1
代码如下(示例):
import win32com.client, os, time
from PyPDF2 import PdfFileWriter, PdfFileReader
###################### 对word加密
def word_encryption(path, password):
# 若加密保存.docx时,覆盖原文件,则无法成功添加密码。但是保存为另一个文件名,则可以添加密码。
# 因此将A存为B,删A,再将B改为A。
dirname, tempname = os.path.split(path)
path_temp = os.path.join(dirname, tempname)
while os.path.exists(path_temp):
tempname = f'{len(tempname)}' + tempname
path_temp = os.path.join(dirname, tempname)
def w_encryption(fp, pt, pw):
word_app = win32com.client.Dispatch('Word.Application')
word_app.Visible = 0
word_app.DisplayAlerts = 0
doc = word_app.Documents.Open(fp, False, False, False, '')
doc.SaveAs2(pt, None, False, pw)
doc.Close()
word_app.Quit()
w_encryption(path, path_temp, password)
os.remove(path) # 删除原文件
os.rename(path_temp, path) # 改临时文件名称为原文件名称
time.sleep(0.5) # 不要删除,不要删除
###################### 对excel加密
def excel_encryption(path, password):
dirname, tempname = os.path.split(path)
path_temp = os.path.join(dirname, tempname)
while os.path.exists(path_temp):
tempname = f'{len(tempname)}' + tempname
path_temp = os.path.join(dirname, tempname)
def e_encryption(fp, pt, pw):
excel_app = win32com.client.Dispatch("Excel.Application")
excel_app.Visible = 0
excel_app.DisplayAlerts = 0
exl = excel_app.Workbooks.Open(fp, False, False, None, '')
exl.SaveAs(pt, None, pw ,'')
exl.Close()
excel_app.Quit()
e_encryption(path, path_temp, password)
os.remove(path) # 删除原文件
os.rename(path_temp, path) # 改临时文件名称为原文件名称
time.sleep(0.5) # 不要删除,不要删除
###################### 对pdf加密
def pdf_encryption(path, password):
dirname, tempname = os.path.split(path)
path_temp = os.path.join(dirname, tempname)
while os.path.exists(path_temp):
tempname = f'{len(tempname)}' + tempname
path_temp = os.path.join(dirname, tempname)
def p_encryption(fp, pt, pw):
pdf_reader = PdfFileReader(fp) #输入你想要操作的pdf文档的位置/名称
pdf_writer = PdfFileWriter()
for page in range(pdf_reader.getNumPages()):
pdf_writer.addPage(pdf_reader.getPage(page))
pdf_writer.encrypt(pw) #括号里面填写密码
with open(pt, 'wb') as out:
pdf_writer.write(out)
p_encryption(path, path_temp, password)
os.remove(path) # 删除原文件
os.rename(path_temp, path) # 改临时文件名称为原文件名称
time.sleep(0.5) # 不要删除,不要删除
###################### 对word加密时读取文件类型判断
def elistdir(path):
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path) and file_path == path: # 排除子路径
elistdir(file_path)
# print(file_path)
elif os.path.splitext(file_path)[1] == '.docx':
if file_path != '':
print(file_path)
try:
word_encryption(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.doc':
if file_path != '':
print(file_path)
try:
word_encryption(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.xlsx':
if file_path != '':
print(file_path)
try:
excel_encryption(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.xls':
if file_path != '':
print(file_path)
try:
excel_encryption(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.pdf':
if file_path != '':
print(file_path)
try:
pdf_encryption(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.txt':
if file_path != '':
print(file_path)
try:
txt_encryption(file_path, key)
except:
pass
# ###################### 对word解密
def word_decryption(path, password):
# 若加密保存.docx时,覆盖原文件,则无法成功添加密码。但是保存为另一个文件名,则可以添加密码。
# 因此将A存为B,删A,再将B改为A。
dirname, tempname = os.path.split(path)
path_temp = os.path.join(dirname, tempname)
while os.path.exists(path_temp):
tempname = f'{len(tempname)}' + tempname
path_temp = os.path.join(dirname, tempname)
def w_decryption(fp, pt, pw):
word_app = win32com.client.Dispatch('Word.Application')
word_app.Visible = 0
word_app.DisplayAlerts = 0
doc = word_app.Documents.Open(fp, False, False, False, key)
doc.SaveAs2(pt, None, False, pw)
doc.Close()
word_app.Quit()
w_decryption(path, path_temp, password)
os.remove(path) # 删除原文件
os.rename(path_temp, path) # 改临时文件名称为原文件名称
time.sleep(0.5) # 不用删除
###################### 对word解密时读取文件类型判断
def dlistdir(path):
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path) and file_path == path: # 排除子路径
dlistdir(file_path)
# print(file_path)
elif os.path.splitext(file_path)[1] == '.docx':
# list_name.append(file_path)
if file_path != '':
print(file_path)
try:
word_decryption(file_path, '')
except:
pass
if __name__ == '__main__':
key = 'xh19970908' # 加密解密密匙
filedir = r"C:\Xu-Data\问题记录" # 指定路径不包含子路径
elistdir(filedir) # 遍历word
print('encrytion sucess\n Waiting...')
# time.sleep(2) # 设置时间随意操作
# dlistdir(filedir) # 遍历word
# print('decrytion Done')
二、代码2
代码如下(示例):
import os
class ecryption(object):
def __init__( self , password , ecryption_path ,save_path ):
self.password = password
self.ecryption_path = ecryption_path
self.save_path = save_path
def efiles(self,):
cmd = r'C:\WinARA\WinRAR.exe a -p%s %s %s' % (password, save_path , ecryption_path) #password为压缩密码
os.system(cmd)
return True
def elistdir(self,):
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path) and file_path == path: # 排除子路径
elistdir(file_path)
# print(file_path)
elif os.path.splitext(file_path)[1] == '.docx':
if file_path != '':
print(file_path)
try:
defiles(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.doc':
if file_path != '':
print(file_path)
try:
defiles(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.xlsx':
if file_path != '':
print(file_path)
try:
defiles(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.xls':
if file_path != '':
print(file_path)
try:
defiles(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.pdf':
if file_path != '':
print(file_path)
try:
defiles(file_path, key)
except:
pass
elif os.path.splitext(file_path)[1] == '.txt':
if file_path != '':
print(file_path)
try:
defiles(file_path, key)
except:
pass
def defiles(self,):
cmd = r'C:\WinARA\WinRAR.exe a -p%s %s %s' % (password, save_path , ecryption_path) #password为压缩密码
os.system(cmd)
return True
if __name__ == '__main__':
f = input('压缩文件夹或者单独文件:')
password = int(input('密码:'))
if f == '文件夹':
ecryption_path1 = r'C:\Users\tuxia\Desktop\files'
save_path1 = r'C:\Users\tuxia\Desktop\xh\files.zip'
ep1 = ecryption( password , ecryption_path1 ,save_path1 )
ep1.efiles()
else:
ecryption_path2 = r'C:\Users\tuxia\Desktop\葛博士-论文.word'
save_path2 = r'C:\Users\tuxia\Desktop\xh\葛博士-论文.zip'
ep2 = ecryption( password , ecryption_path2 ,save_path2 )
ep2.defiles()
三、代码3
代码如下(示例):
import os
password = ""
dirpath = r'C:\Users\tuxia\Desktop\xh'#待压缩的文件路径及文件
outFullName = r'C:\Users\tuxia\Desktop\xh.zip'#压缩文件的输出路径及文件名
cmd = r'C:\WinARA\WinRAR.exe a -p%s %s %s' % ('123456', outFullName, dirpath)#password为压缩密码
os.system(cmd)
import os
password = ""
dirpath = r'C:\Users\tuxia\Desktop\xh\t1.txt' #待压缩的文件路径及文件
outFullName = r'C:\Users\tuxia\Desktop\xh\t1.rar'#压缩文件的输出路径及文件名
cmd = r'C:\"Program Files"\WinRAR\WinRAR.exe a -p%s %s %s' % (password, outFullName, dirpath)#password为压缩密码
os.system(cmd)