2023-2024-1 20232817《Linux内核原理与分析》第十二周作业
Python实现Zip文件的暴力破解
实验原理
zipfile
首先我们进入 Code
目录:
cd Code
创建一个用于我们实验的目录 deZip
:
mkdir attack_zip
进入 attack_zip
目录:
cd attack_zip
现在我们创建 1.txt
文件:
touch 1.txt
将 1.txt
文件压缩成加密的 1.zip
文件,密码为 1314
:
zip -r 1.zip 1.txt -P 1314
编写demo.py
import zipfile
try:
with zipfile.ZipFile('1.zip') as zFile: #创建 ZipFile 对象
#解压文件
zFile.extractall(path='./', pwd=b'1314')
print('Extract the Zip file successfully!')
except:
print('Extract the Zip file failed!')
将代码保存为 demo.py
我们测试一下是否能正确解压文件:
argparse
argparse 的用法:
demo.py
import argparse
parser = argparse.ArgumentParser(description='Regards to your name.')
parser.add_argument('-n', dest='m_name', type=str, help='your name')
options = parser.parse_args()
print('Hello',options.m_name)
运行demo.py
暴力破解 Zip 文件
基本思路就是我们不断去读取密码字典尝试解压带密码的 Zip 文件,如果成功则表示这个密码正确,失败则继续读取密码字典中的密码并尝试解压缩,直到解压缩成功或者密码字典中的密码都尝试一遍。
我们先写一个函数专门用于解压缩 Zip 文件,这个压缩函数有三个参数 zipFile
、password
,savePath
。含义如下:
zipFile
表示一个 ZipFile 对象。password
表示解压 ZipFile 的密码。savePath
表示解压后文件存储的路径。
这个函数在尝试密码之后会返回一个布尔值,如果解压成功会返回 True
,如果失败则会返回 False
。
import zipfile
import argparse
import os
from os.path import *
def tryZipPwd(zipFile, password, savePath):
try:
zipFile.extractall(path=savePath, pwd=password.encode('utf-8'))
print('[+] Zip File decompression success,password: %s' % (password))
return True
except:
print('[-] Zip File decompression failed,password: %s' % (password))
return False
def main():
# 这里用描述创建了 ArgumentParser 对象
parser = argparse.ArgumentParser(description='Brute Crack Zip')
# 添加 - H 命令 dest 可以理解为咱们解析时获取 - H 参数后面值的变量名, help 是这个命令的帮助信息
parser.add_argument('-f', dest='zFile', type=str, help='The zip file path.')
parser.add_argument('-w', dest='pwdFile', type =str, help='Password dictionary file.')
zFilePath = None
pwdFilePath = None
try:
options = parser.parse_args()
zFilePath = options.zFile
pwdFilePath = options.pwdFile
except:
print(parser.parse_args(['-h']))
exit(0)
if zFilePath == None or pwdFilePath == None:
print(parser.parse_args(['-h']))
exit(0)
with zipfile.ZipFile(zFilePath) as zFile:
with open(pwdFilePath) as f:
for pwd in f.readlines():
p,f = split(zFilePath)
dirName = f.split('.')[0]
dirPath = join(p, dirName)
try:
os.mkdir(dirPath)
except:
pass
ok = tryZipPwd(zFile, pwd.strip('\n'), dirPath)
if ok:
break
if __name__ == '__main__':
main()
创建一个用于测试的密码字典 pwd.txt
:
vim pwd.txt
内容如下:
测试一下程序