与以前不同,生成随机字符串

时间:2016-03-10 01:51:12

标签: python

我正在尝试在Python中使用密码破解程序作为练习,并且我注意到它平均需要586,634次迭代来破解密码“嘿”。我认为它太高了,因为它可以自由生成一个可能已经被检查的随机字符串。例如,当它已经发现它不起作用时,它可以生成以下内容并使用额外的时间。

a!? h[jjpco$w 01g ,{{1 }, a5b a!?

那么如何阻止Python反复生成相同的字符串?

这是我的代码(它生成的长度由输入的长度决定):

01g

1 个答案:

答案 0 :(得分:1)

试一试。它生成所有可能的3个字母组合。你可以用你想要的长度替换2。另请注意,我将product生成的迭代器转换为list。如果你只需要循环一次,最好不要先将它转换为list,因为这会占用更多的内存。只需摆脱list()函数调用。

import itertools
import string

letters = string.lowercase + string.uppercase + string.punctuation + string.digits
all_possible =  list(itertools.product(letters, repeat=3))
test_pws = ['hey', 'h9!', '!!!']
for i,possible_pw in enumerate(all_possible):
    pw = "".join(possible_pw)
    if pw  in test_pws:
        print 'Found ', pw, ' at iteration ', i

print all_possible[:5]
print len(all_possible)
print len(set(all_possible))
print all_possible[-5:]

输出

Found  hey  at iteration  62252
Found  h9!  at iteration  70646
Found  !!!  at iteration  464412

[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'a', 'd'), ('a', 'a', 'e')]
830584
830584
[('9', '9', '5'), ('9', '9', '6'), ('9', '9', '7'), ('9', '9', '8'), ('9', '9', '9')]
相关问题