Python实例题:Python实现Zip文件的暴力破解
目录
Python实例题
题目
代码实现
实现原理
多线程处理:
密码尝试:
密码生成策略:
关键代码解析
1. 工作线程函数
2. 密码生成
3. 主函数流程
使用说明
基本用法:
使用字典文件:
自定义字符集和密码长度:
增加线程数:
显示详细信息:
扩展建议
增强功能:
性能优化:
用户界面:
安全增强:
Python实例题
题目
Python实现Zip文件的暴力破解
代码实现
import zipfile
import argparse
import threading
import queue
import time
import string
import itertools
from datetime import timedelta
from colorama import init, Fore, Style# 初始化colorama
init(autoreset=True)class ZipCracker:def __init__(self, zip_file, threads=4, verbose=False):"""初始化Zip文件破解器Args:zip_file: 要破解的Zip文件路径threads: 线程数,默认为4verbose: 是否显示详细信息,默认为False"""self.zip_file = zip_fileself.threads = threadsself.verbose = verboseself.password_queue = queue.Queue()self.found = threading.Event()self.lock = threading.Lock()self.start_time = Noneself.attempts = 0self.results = []def load_passwords_from_file(self, wordlist_file):"""从字典文件加载密码Args:wordlist_file: 字典文件路径Returns:成功加载返回True,失败返回False"""try:with open(wordlist_file, 'r', encoding='utf-8') as f:passwords = [line.strip() for line in f.readlines()]for password in passwords:self.password_queue.put(password)print(f"{Fore.BLUE}[*] 从字典文件加载了 {len(passwords)} 个密码")return Trueexcept Exception as e:print(f"{Fore.RED}[-] 加载字典文件失败: {e}")return Falsedef generate_passwords(self, charset, min_length, max_length):"""生成密码组合Args:charset: 字符集min_length: 最小长度max_length: 最大长度"""print(f"{Fore.BLUE}[*] 生成密码组合: 字符集大小={len(charset)}, 长度范围={min_length}-{max_length}")for length in range(min_length, max_length + 1):for password in itertools.product(charset, repeat=length):if self.found.is_set():returnself.password_queue.put(''.join(password))def worker(self):"""工作线程函数"""zf = zipfile.ZipFile(self.zip_file)while not self.found.is_set() and not self.password_queue.empty():password = self.password_queue.get()try:# 尝试解压文件zf.extractall(pwd=password.encode())# 如果没有抛出异常,说明密码正确with self.lock:self.found.set()self.results.append(password)elapsed_time = time.time() - self.start_timeprint(f"{Fore.GREEN}[+] 找到密码: {password}")print(f"{Fore.YELLOW}[!] 破解完成,耗时: {timedelta(seconds=elapsed_time)}")print(f"{Fore.YELLOW}[!] 尝试次数: {self.attempts}")breakexcept (RuntimeError, zipfile.BadZipFile):# 密码错误passexcept Exception as e:if self.verbose:print(f"{Fore.RED}[-] 尝试密码 {password} 时出错: {e}")# 更新尝试次数with self.lock:self.attempts += 1if self.verbose and self.attempts % 1000 == 0:elapsed_time = time.time() - self.start_timeattempts_per_second = self.attempts / elapsed_time if elapsed_time > 0 else 0print(f"{Fore.CYAN}[*] 已尝试: {self.attempts} 次, 速度: {attempts_per_second:.2f} 次/秒")self.password_queue.task_done()def run(self):"""运行破解程序"""if self.password_queue.empty():print(f"{Fore.RED}[-] 密码队列为空,请先加载字典或生成密码")return Falseprint(f"{Fore.BLUE}[*] 开始破解 {self.zip_file}")print(f"{Fore.BLUE}[*] 使用 {self.threads} 个线程")self.start_time = time.time()# 创建工作线程threads = []for _ in range(self.threads):t = threading.Thread(target=self.worker)t.daemon = Truet.start()threads.append(t)# 等待所有线程完成for t in threads:t.join()# 检查是否找到密码if not self.results:elapsed_time = time.time() - self.start_timeprint(f"{Fore.RED}[-] 未能找到密码,已尝试 {self.attempts} 次,耗时: {timedelta(seconds=elapsed_time)}")return Falsereturn Truedef main():parser = argparse.ArgumentParser(description='Zip文件暴力破解工具')parser.add_argument('-f', '--file', required=True, help='要破解的Zip文件')parser.add_argument('-w', '--wordlist', help='密码字典文件')parser.add_argument('-c', '--charset', default=string.ascii_lowercase + string.digits, help='字符集 (默认: 小写字母和数字)')parser.add_argument('-min', '--min-length', type=int, default=1, help='最小密码长度')parser.add_argument('-max', '--max-length', type=int, default=6, help='最大密码长度')parser.add_argument('-t', '--threads', type=int, default=4, help='线程数')parser.add_argument('-v', '--verbose', action='store_true', help='显示详细信息')args = parser.parse_args()# 检查文件是否存在if not os.path.exists(args.file):print(f"{Fore.RED}[-] 文件不存在: {args.file}")return# 检查文件是否是有效的Zip文件try:with zipfile.ZipFile(args.file) as zf:if not zf.testzip():print(f"{Fore.YELLOW}[!] Zip文件没有加密,无需破解")returnexcept zipfile.BadZipFile:print(f"{Fore.RED}[-] 不是有效的Zip文件: {args.file}")returnexcept Exception as e:print(f"{Fore.RED}[-] 检查Zip文件时出错: {e}")return# 创建破解器实例cracker = ZipCracker(args.file, args.threads, args.verbose)# 加载密码if args.wordlist:if not cracker.load_passwords_from_file(args.wordlist):print(f"{Fore.RED}[-] 无法加载字典文件,使用字符集生成密码")cracker.generate_passwords(args.charset, args.min_length, args.max_length)else:cracker.generate_passwords(args.charset, args.min_length, args.max_length)# 运行破解cracker.run()if __name__ == "__main__":main()
实现原理
这个 Zip 文件暴力破解工具基于以下核心技术实现:
-
多线程处理:
- 使用队列管理待测试的密码
- 多线程并行尝试密码,提高破解效率
- 找到正确密码后立即停止所有线程
-
密码尝试:
- 使用 Python 的 zipfile 库尝试解压文件
- 捕获密码错误异常,区分不同类型的错误
- 处理各种可能的编码问题
-
密码生成策略:
- 支持从字典文件加载密码
- 支持自定义字符集生成密码组合
- 可配置密码长度范围
关键代码解析
1. 工作线程函数
def worker(self):zf = zipfile.ZipFile(self.zip_file)while not self.found.is_set() and not self.password_queue.empty():password = self.password_queue.get()try:zf.extractall(pwd=password.encode())with self.lock:self.found.set()self.results.append(password)print(f"{Fore.GREEN}[+] 找到密码: {password}")breakexcept (RuntimeError, zipfile.BadZipFile):passexcept Exception as e:if self.verbose:print(f"{Fore.RED}[-] 尝试密码 {password} 时出错: {e}")with self.lock:self.attempts += 1if self.verbose and self.attempts % 1000 == 0:attempts_per_second = self.attempts / (time.time() - self.start_time)print(f"{Fore.CYAN}[*] 已尝试: {self.attempts} 次, 速度: {attempts_per_second:.2f} 次/秒")self.password_queue.task_done()
2. 密码生成
def generate_passwords(self, charset, min_length, max_length):print(f"{Fore.BLUE}[*] 生成密码组合: 字符集大小={len(charset)}, 长度范围={min_length}-{max_length}")for length in range(min_length, max_length + 1):for password in itertools.product(charset, repeat=length):if self.found.is_set():returnself.password_queue.put(''.join(password))
3. 主函数流程
def main():parser = argparse.ArgumentParser(description='Zip文件暴力破解工具')# 添加参数...args = parser.parse_args()if not os.path.exists(args.file):print(f"{Fore.RED}[-] 文件不存在: {args.file}")returntry:with zipfile.ZipFile(args.file) as zf:if not zf.testzip():print(f"{Fore.YELLOW}[!] Zip文件没有加密,无需破解")returnexcept zipfile.BadZipFile:print(f"{Fore.RED}[-] 不是有效的Zip文件: {args.file}")returncracker = ZipCracker(args.file, args.threads, args.verbose)if args.wordlist:if not cracker.load_passwords_from_file(args.wordlist):cracker.generate_passwords(args.charset, args.min_length, args.max_length)else:cracker.generate_passwords(args.charset, args.min_length, args.max_length)cracker.run()
使用说明
-
基本用法:
python zip_cracker.py -f encrypted.zip
这会使用默认字符集(小写字母和数字)尝试破解 Zip 文件。
-
使用字典文件:
python zip_cracker.py -f encrypted.zip -w passwords.txt
-
自定义字符集和密码长度:
python zip_cracker.py -f encrypted.zip -c "abcdefghijklmnopqrstuvwxyz0123456789" -min 3 -max 8
-
增加线程数:
python zip_cracker.py -f encrypted.zip -t 16
-
显示详细信息:
python zip_cracker.py -f encrypted.zip -v
扩展建议
-
增强功能:
- 添加更多密码生成策略(如掩码攻击、规则引擎)
- 实现分布式破解支持
- 添加密码复杂度分析
- 支持恢复部分损坏的 Zip 文件
-
性能优化:
- 使用 C 扩展提高密码尝试速度
- 优化线程管理和队列操作
- 添加结果缓存,避免重复尝试
-
用户界面:
- 开发图形界面版本
- 添加进度条和破解状态显示
- 支持暂停和恢复破解过程
-
安全增强:
- 添加 IP 封禁规避策略
- 实现代理池支持
- 优化内存使用,处理大字典文件