You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提升Python SHA1哈希暴力破解器性能及并发模块选型咨询

三个Python并发模块的区别与选型
  • threading:Python标准线程模块,受CPython全局解释器锁(GIL)限制,同一时间仅能有一个线程执行Python字节码,仅对IO密集型场景有加速效果。CPU密集型任务下多线程不仅无法提速,还会因为线程切换产生额外开销,性能反而可能下降。
  • concurrent.futures:高层并发封装API,本身没有新增并发原语,只是简化了线程池(ThreadPoolExecutor)和进程池(ProcessPoolExecutor)的调用逻辑,底层能力还是依赖threading和multiprocessing实现。
  • multiprocessing:多进程模块,每个进程持有独立的Python解释器和GIL,可以完全利用多核CPU的计算资源,专门适配CPU密集型场景,缺点是进程启动、进程间通信的开销比线程更高。

场景选型结论

直接选择multiprocessing,或者concurrent.futures封装的ProcessPoolExecutor即可。

其余两个模块不适用的原因

  • threading:你的暴力破解属于纯CPU计算密集任务,GIL会完全限制线程并行能力,开线程没有任何加速效果。
  • 如果你使用concurrent.futures.ThreadPoolExecutor,本质和直接用threading没有区别,同样受GIL限制无法提速。只有用到它封装的进程池能力时才有效,因此它本身不是核心选型,只是可选的上层语法糖。
现有代码的提速方案

1. 先修正代码基础问题

你提供的是Python2语法,Python3环境下无法直接运行,首先调整语法、减少无意义的类型转换开销:

import time
import hashlib
import itertools
import base64
import multiprocessing as mp

# 直接用bytes定义字符集,避免后续频繁str转bytes的开销
charset = b"abcdefghijklmnopqrstuvwxyz0123456789"
good = "" # 替换为你的目标哈希值
start = time.time()
# 多进程下用于通知所有进程终止的信号
found_event = mp.Event()

def encrypt(password_chunk):
    if found_event.is_set():
        return
    for password_tuple in password_chunk:
        password = b"".join(password_tuple)
        hsah = hashlib.sha1(password).digest()
        # 替换原来的base64 encode逻辑,处理默认换行符
        hsah = base64.b64encode(hsah).rstrip(b"\n")
        # 此处补充你的自定义salt逻辑
        hsah = hashlib.sha1(hsah).hexdigest()
        if hsah == good:
            print(f"password found!: {password.decode()}")
            print(f"耗时: {time.time() - start}s")
            found_event.set()
            return password

if __name__ == "__main__":
    passwords = itertools.product(charset, repeat=7)
    cpu_count = mp.cpu_count()
    # 按块拆分任务,避免进程间通信过于频繁
    chunk_size = 10000
    chunks = []
    chunk = []
    for p in passwords:
        chunk.append(p)
        if len(chunk) == chunk_size:
            chunks.append(chunk)
            chunk = []
    if chunk:
        chunks.append(chunk)
    
    with mp.Pool(cpu_count) as pool:
        for result in pool.imap_unordered(encrypt, chunks):
            if result is not None:
                pool.terminate()
                break

2. 其他优化手段

  • 所有字符串逻辑统一用bytes处理,避免str和bytes频繁互转,可降低30%以上的无谓开销
  • 任务按块分配给进程,不要单个密码发起一次进程调用,大幅降低进程间通信开销
  • 改用PyPy解释器运行代码,纯循环计算场景下比CPython速度高2~5倍
  • 7位长度36字符集的总组合数超过780亿,就算8核CPU满负载每秒跑100万次,也需要连续跑9天以上,建议优先通过密码特征缩小字符集范围,或改用hashcat等专业哈希破解工具,速度比纯Python实现高2~3个数量级。

内容的提问来源于stack exchange,提问作者Ferxiss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:42:02