python 破解zip文件
参考于:《python绝技:运用python成为顶级黑客》
运用python破解zip文件主要是zipfile模块和extractall方法
zipfile模块可以实现对zip文件的创建,解压,和获取解压后文件信息
首先我们新建一个名为evil密码为secret的zip文件
import zipfile
zFile=zipfile.ZipFile('evil.zip') #将zip文件实例化为该模块可操作的对象
###当然zFile=zipfile.ZipFile(' ')中也可填入文件地址,例如r"C:\Users\Desktop\evil.zip" (字符串前加'r'是为了防止字符转义)
调用extractall方法:
import zipfile
zFile=zipfile.ZipFile("evil.zip")
zFile.extractall(pwd='secret')
我们会得到这样一个报错:
Traceback (most recent call last):
File "G:/PycharmProjects/untitled1/zipfile0.py", line 3, in <module>
zFile.extractall(pwd="secret")
File "D:\Anaconda3\lib\zipfile.py", line 1501, in extractall
self._extract_member(zipinfo, path, pwd)
File "D:\Anaconda3\lib\zipfile.py", line 1554, in _extract_member
with self.open(member, pwd=pwd) as source, \
File "D:\Anaconda3\lib\zipfile.py", line 1336, in open
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
TypeError: pwd: expected bytes, got str
TypeError: pwd: expected bytes, got str 提示我们pwd格式应该为bytes
使用 .encode(‘asiic’)将其转换为bytes
在报错中,我们也可以看到对extractall方法的部分说明:
extractall(path,members,pwd)
它可以接收三个参数:
path是解压的路径(默认为解压文件所在路径),members是需要解压出来的文件(默认为全部文件),pwd是密码
修改后:
import zipfile
zFile=zipfile.ZipFile('evil.zip')
zFile.extractall(pwd='secret'.encode('ascii'))
运行解压成功
在该目录下多了一个名为evil的文件
代码改进
为了破解zip文件,需要新建一个字典,这里字典名为dictionary.txt(当然也可以自己去下载相关的字典)
dictionary.txt内容:
apple
orange
egg
lemon
grapes
secret
strawberry
password
改进后代码:
import zipfile
zFile=zipfile.ZipFile('evil.zip')
passwordfile=open('dictionary.txt')
for line in passwordfile.readlines(): #逐行读取
password=line.strip('\n') #去除换行符
try:
zFile.extractall(pwd=password.encode('ascii'))
print('the password is: '+ password)
break #读取到正确密码就退出循环
except Exception as e: #打印报错
print(e)
运行结果:
Bad password for file <ZipInfo filename='evil/note_to_adam.txt' compress_type=deflate filemode='-rw-r--r--' file_size=171 compress_size=156>
Bad password for file <ZipInfo filename='evil/note_to_adam.txt' compress_type=deflate filemode='-rw-r--r--' file_size=171 compress_size=156>
Bad password for file <ZipInfo filename='evil/note_to_adam.txt' compress_type=deflate filemode='-rw-r--r--' file_size=171 compress_size=156>
Bad password for file <ZipInfo filename='evil/note_to_adam.txt' compress_type=deflate filemode='-rw-r--r--' file_size=171 compress_size=156>
Bad password for file <ZipInfo filename='evil/note_to_adam.txt' compress_type=deflate filemode='-rw-r--r--' file_size=171 compress_size=156>
the password is: secret #读取到正确密码时退出循环