2022年 11月 3日

Python:暴力破解密码

简介:暴力破解密码的方式一般是枚举法进行破译尝试,通过一次次不同的输入尝试从而得出最终的密码,所以密码的长度和复杂性就尤为重要。本文仅以范例,警示大家在创建密码的时候,应当尽量选择组合复杂度高的,有一定长度的密码,而不是123456之类的简单密码。

破解的思路:
1、获取目标密码长度,一般为4,6,12,15,18位长度。
2、获取目标密码组成的范围,一般为数字,小写字母,大写字母,特殊符号
3、组装密码,通过itertools模块组装。Python:常见排列组合问题处理
4、枚举破译。

例如生活中最常见的取款密码一般为6位,如果没有一天3次输错就锁定卡的情况。让我们来看看不同长度下的取款密码能撑多久。

破解密码范例:

import random
import itertools
import time


def test_bank_card_password(password_length=6):
    data = "0123456789"
    bank_card_password = str(random.randint(0, int("9" * password_length)))
    if len(bank_card_password) < password_length:
        bank_card_password = "0" * (password_length - len(bank_card_password)) + bank_card_password

    print(f"银行卡密码为:{bank_card_password}")

    num = 0
    for i in itertools.product(data, repeat=password_length):
        guess = "".join(i)
        if bank_card_password == guess:
            print(f"当前密码长度:{password_length}, 猜测的密码为:{guess}。实际密码为:{bank_card_password},尝试次数:{num},破解成功。")
            break
        num += 1


if __name__ == '__main__':
    start = time.time()
    test_bank_card_password(6)
    end = time.time()
    print(f"破解耗时:{round(end - start, 2)}秒")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

当密码长度为6位时:可以看到破解这类密码如果没有锁卡限制,0.5秒不到就能完成密码破解。

图片

当密码长度为7位时:7位数字密码长度,耗时1.61秒,耗时增加了3倍多。

图片

当密码长度为8位时:8位数字密码长度,耗时20.56秒,耗时增加了41倍多。

图片

当密码长度为9位时:9位数字密码长度,耗时212秒,耗时增加了400倍多。

图片

由此可见,在记忆有余的情况下,应该尽量选择复杂组合,长度偏长一点的密码。

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

在这里插入图片描述