参考链接:https://blog.csdn.net/aaahtml/article/details/116836899
参考链接:https://blog.csdn.net/weixin_42350212/article/details/117031929
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple PyPDF2
import PyPDF2
import itertools
# 加密PDF
def encrypt(old_Path, new_Path):
""" :param old_Path: 待加密文件的路径名 :param new_Path: 加密之后的文件路径名 """
with open(old_Path, 'rb') as pdfFile:
pdfReader = PyPDF2.PdfFileReader(pdfFile)
# 创建pdfWriter对象用于写出PDF文件
pdfWriter = PyPDF2.PdfFileWriter()
# pdf对象加入到pdfWriter对象中
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
# 密码设置为5243
pdfWriter.encrypt('5243')
with open(new_Path, 'wb') as resultPDF:
pdfWriter.write(resultPDF)
print('加密成功!')
# 数字解密
def decrypt(old_Path, new_Path):
""" :param old_Path: 待加密文件的路径名 :param new_Path: 加密之后的文件路径名 """
with open(old_Path, 'rb') as pdfFile:
pdfReader = PyPDF2.PdfFileReader(pdfFile)
pdfWriter = PyPDF2.PdfFileWriter()
# 判断文件是否加密
if pdfReader.isEncrypted:
# 判断密码是否正确
for i in range(10000):
# 生成四位数密码
pwd = str(i).zfill(4)
if pdfReader.decrypt(pwd):
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
with open(new_Path, 'wb') as resultFile:
pdfWriter.write(resultFile)
print('成功了!密码是:'+pwd)
else:
print('密码错了!哼~~~')
else:
print('没有加密呀~~~')
# 密码本解密
def decryptBypass(password_Path, pdf_Path):
passw = []
file = open(password_Path)
for line in file.readlines():
passw.append(line.strip())
file.close()
pdf_reader = PyPDF2.PdfFileReader(pdf_Path)
for i in passw:
if pdf_reader.decrypt(i):
print(f'破解成功,密码为{i}')
else:
print(f'破解不成功,密码{i}错误')
# 无密码本,穷举解密
def decryptByexhaustive(pdf_Path):
mylist = ("".join(x) for x in itertools.product("12345a", repeat=5))
pdf_reader = PyPDF2.PdfFileReader(pdf_Path)
while True:
i = next(mylist)
if pdf_reader.decrypt(i):
print(f'破解成功,密码为{i}')
break
else:
print(f'破解不成功,密码{i}错误')
if __name__ == '__main__':
# encrypt("../pdfadad.pdf", "pdfadad3.pdf")
# decryptBypass("password.txt", "pdfadad3.pdf")
decryptByexhaustive("pdfadad3.pdf")
# decrypt("pdfadad3.pdf", "pdfadad4.pdf")