利用Python多线程模块以及Hashlib模块破解密码

  本代码主要包括以下几个部分:

    1. 从网上下载密码字典(github),在下载之前判断,一旦已经文件已经存在,则无需再下载;

    2. 利用多线程threading以及Queue模块对密码字典进行hash计算,并且一旦发现queue队列里已经有内容(即猜中的密码),则不要再创建子线程,从而停止程序,否则需要遍历整个字典

 

import hashlib
import sys
import requests
import os
import threading
import queue



class HashCracker:
    def __init__(self,url,hashed_value):
        self.url = url
        self.filename = url.split("/")[-1]      #从URL中提取出文件名称
        self.hashed_value = hashed_value
        self.q = queue.Queue()                  #利用Queue队列实现线程之间的变量共享和判断,一旦发现queue.empty非真,表明已经发现密码,则无需继续循环创建子线程,从而推出程序
        if not os.path.exists(self.filename):
            self.get_passwordlist(url)          #如果文件不存在,则从网上下载该文件
    
    def get_passwordlist(self):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0'
        }
        try:      
            response = requests.get(self.url, headers=headers).text
            with open(self.filename, 'w') as f:
                f.write(response)
                print("Downloaded Successfully!")
            return 
        except:
            print("Faliled to download password list!")
            sys.exit(0)
    
    def guess_password(self, password):
        
        hashobj = hashlib.sha1()
        hashobj.update(password.encode('utf-8'))
            
        if self.hashed_value == hashobj.hexdigest():
            print("Found password: %s" % password)
            self.q.put(password)                   #发现密码hash计算值一致,则将该密码放到queue队列中,该队列可被主进程以及其他子线程看到
            

    def crack_password(self):
        with open(self.filename, 'r') as f:
            for line in f.readlines():
                if self.q.empty():
                    t = threading.Thread(target=self.guess_password, args=(line.strip(),))
                    t.start()
        
        if not self.q.empty():
            print(self.q.get())
        else:
            print("Failed to crack!")


def banner():
    banner = """
        ******************************************************************
        ******************************************************************
                           SHA Cracking Tool by Jason Wong V1.0
        ******************************************************************
        ******************************************************************
    """
    print(banner)



if __name__ == "__main__":
    banner()
    hashed_value = input("Enter Hash Value to Crack: ")
    url = 'https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10-million-password-list-top-1000000.txt'
    hashcracker = HashCracker(url, hashed_value)
    hashcracker.crack_password()
   

 

posted @ 2022-04-24 10:57  Jason_huawen  阅读(283)  评论(1编辑  收藏  举报