Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random string unlike previous

Tags:

python

I'm trying to make a password cracker in Python as practice, and I've noticed that it takes on average 586,634 iterations to crack the password "hey". I'm thinking it's so high because it can freely generate a random string that may have already been checked. For example, it could generate the following and use extra time doing so, when it's already found that it doesn't work.

a!?, h[j, jpc, o$w, 01g, a5b, a!?, 01g

So how do I stop Python from generating the same string over and over?

Here's my code (the length that it generates is determined by the input's length):

while crack!=password:
        i+=1
        crack=''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(length))
like image 682
Shane Smiskol Avatar asked Jan 19 '26 07:01

Shane Smiskol


1 Answers

Try this out. It generates all possible 3 letter combinations. You can replace 2 with whatever length you want. Also note that I turned the iterator that results from product into a list. If you just need to loop over it once, it is better to not convert it to a list first, since that eats up more memory. Just get rid of the list() function call.

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:]

Output

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')]
like image 96
Garrett R Avatar answered Jan 20 '26 19:01

Garrett R