如何为字母和字母数字密码创建暴力密码破解程序?

How to create a brute-force password cracker for alphabetical and alphanumerical passwords?

我需要为学校制作小程序来暴力破解不同类型的密码;我想创建一个蛮力 python 代码,它将 运行 通过字母和字母数字密码的所有可能组合,并给我密码和破解所需的时间。

我对纯数字密码做了同样的事情,得到了这个:

import datetime as dt

Password4 = 123456

def crack_password():
    start = dt.datetime.now()
    for n in range(1000000):
        password_guess = '{0:04d}'.format(n)
             if password_guess == str(Password4):
                end = dt.datetime.now()
                print("Password found: {} in {}".format(password_guess, end - start))
               break
    guesses = crack_password()

然后我尝试对 alphabet/alphanumerical 密码做一些类似的事情,但无论我尝试什么都没有用:

    import random

    letters = [str(i) for i in range('a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p')]
    s = [''.join([a,b,c,d,e,f,g,h]) for a in letters for b in letters for c   in letters for d in letters for e in letters for f in letters for g in letters  for h in letters]
    random.shuffle(s)
    real_password = 'aaaaaaaa'
    i = 0

    for code in s:
        if code == real_password:
            print()
            print('The password is: ', code)
             break
        else:
            i += 1
            print(i, ' failures', end='\r')

程序包括失败次数或找到密码所花费的时间是至关重要的,这就是为什么我不能简单地制作一个密码生成器。

一个几乎可以完全保留当前代码的可能选项是使用以下 "digits":0-9a-z 转换为基数 36。如果您在 range(36**n).

中搜索,这将为您提供 n 个字符的所有可能的字母数字组合

使用 How to convert an integer in any base to a string? 中的简化函数:

def baseN(num, b=36, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
    return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])

然后您可以像示例中那样遍历数字:

>>> for i in range(10000, 10005):
...     print(baseN(i).zfill(5))
...
007ps
007pt
007pu
007pv
007pw

要得到所有3个字母的可能性,你可以循环如下:

for i in range(36**3):
    possible = baseN(i).zfill(3)

这是一种天真的暴力破解方法,可以猜测数字 (string.digits) 和小写字母 (string.ascii_lowercase)。您可以使用 itertools.product 并将 repeat 设置为当前猜测的密码长度。您可以从 1 个字符密码(或任何您的下限)开始,然后也将其限制在最大长度。然后 return 当你找到匹配时。

import itertools
import string

def guess_password(real):
    chars = string.ascii_lowercase + string.digits
    attempts = 0
    for password_length in range(1, 9):
        for guess in itertools.product(chars, repeat=password_length):
            attempts += 1
            guess = ''.join(guess)
            if guess == real:
                return 'password is {}. found in {} guesses.'.format(guess, attempts)
            # uncomment to display attempts, though will be slower
            #print(guess, attempts)

print(guess_password('abc'))

输出

a 1
b 2
c 3
d 4
...
aba 1369
abb 1370
password is abc. found in 1371 guesses.