python枚举法爆破密码

import itertools
import zipfile
import rarfile
import os
import time
import threading
from queue import Queue
from datetime import datetime, timedelta

start_time = time.time()  # 记录总测试开始时间


def try_passwords_from_queue(filename, password_queue, file_format):
    """
    从队列中尝试密码破解压缩包的密码。

    :param filename: 压缩包文件路径
    :param password_queue: 密码队列
    :param file_format: 压缩包格式 ('zip' 或 'rar')
    :return: 如果找到密码则返回 True,否则返回 False
    """

    def test_password(password):
        try:
            if file_format == 'zip':
                with zipfile.ZipFile(filename) as zf:
                    zf.extractall(pwd=password.encode())
            elif file_format == 'rar':
                with rarfile.RarFile(filename) as rf:
                    rf.extractall(pwd=password)
            return True
        except (RuntimeError, rarfile.BadRarFile, rarfile.RarWrongPassword):
            return False

    while not password_queue.empty():
        password = password_queue.get()
        if test_password(password):
            with open('password.txt', 'a') as f:
                f.write(f"{filename} {password}\n")
            print(f"密码找到: {password}")
            print(f"开始解压文件到当前目录...")
            if file_format == 'zip':
                with zipfile.ZipFile(filename) as zf:
                    zf.extractall(path=os.getcwd())
            elif file_format == 'rar':
                with rarfile.RarFile(filename) as rf:
                    rf.extractall(path=os.getcwd())
            print(f"解压完成。")
            return True
        password_queue.task_done()

    # 计算每秒测试次数
    global start_time
    elapsed_time = time.time() - start_time
    passwords_tested = password_queue.qsize()
    passwords_per_second = passwords_tested / elapsed_time
    print(f"每秒测试次数: {passwords_per_second:.2f}")

    return False


def generate_password_list(chars, max_length):
    """
    生成所有可能的密码组合。

    :param chars: 密码字符集
    :param max_length: 密码最大长度
    :return: 密码组合生成器
    """
    for length in range(1, max_length + 1):
        yield from (''.join(p) for p in itertools.product(chars, repeat=length))


def estimate_time_and_combinations(chars, max_length):
    """
    估计密码破解的时间和总组合次数。

    :param chars: 密码字符集
    :param max_length: 密码最大长度
    :return: 总组合数和估计时间
    """
    total_combinations = sum(len(chars) ** length for length in range(1, max_length + 1))

    # 估计时间:假设每秒尝试1000个密码
    estimated_time_seconds = total_combinations / 1000
    estimated_time_minutes = estimated_time_seconds / 60
    estimated_time_hours = estimated_time_minutes / 60

    return total_combinations, estimated_time_seconds, estimated_time_minutes, estimated_time_hours


def calculate_completion_time(estimated_time_seconds):
    """
    计算预计完成时间。

    :param estimated_time_seconds: 预计所需时间(秒)
    :return: 预计完成时间的字符串
    """
    current_time = datetime.now()
    completion_time = current_time + timedelta(seconds=estimated_time_seconds)
    return completion_time.strftime('%Y-%m-%d %H:%M:%S')


def main():
    filename = r'F:\Develop\pyproject\pythonProject\破解压缩包\wyh.rar'  # 修改为你的文件路径
    file_format = 'rar'  # 压缩包格式,'zip' 或 'rar'
    max_length = 6  # 密码最大长度

    # 密码字符集
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789'

    # 估计组合次数和破解时间
    total_combinations, estimated_time_seconds, estimated_time_minutes, estimated_time_hours = estimate_time_and_combinations(
        chars, max_length)

    print(f"密码长度: {max_length}")
    print(f"总组合数: {total_combinations}")
    print(f"估计时间: {estimated_time_seconds:.2f} 秒")
    print(f"估计时间: {estimated_time_minutes:.2f} 分钟")
    print(f"估计时间: {estimated_time_hours:.2f} 小时")

    # 计算预计完成时间
    estimated_completion_time = calculate_completion_time(estimated_time_seconds)
    print(f"预计完成时间: {estimated_completion_time}")

    # 生成所有可能的密码组合
    password_list = generate_password_list(chars, max_length)

    # 将密码组合放入队列
    password_queue = Queue()
    for password in password_list:
        password_queue.put(password)

    # 计算开始时间
    global start_time
    start_time = time.time()

    # 创建线程池
    num_threads = min(16, os.cpu_count() * 2 or 1)  # 使用更多的线程
    threads = []
    for _ in range(num_threads):
        thread = threading.Thread(target=try_passwords_from_queue, args=(filename, password_queue, file_format))
        thread.start()
        threads.append(thread)

    # 等待所有线程完成
    for thread in threads:
        thread.join()

    if password_queue.empty():
        print("密码未找到.")

    # 计算结束时间
    end_time = time.time()

    elapsed_time = end_time - start_time
    print(f"实际时间: {elapsed_time:.2f} 秒")
    print(f"实际时间: {elapsed_time / 60:.2f} 分钟")
    print(f"实际时间: {elapsed_time / 3600:.2f} 小时")


if __name__ == "__main__":
    main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值