Python Brute Force algorithm

Madushan picture Madushan · Jul 31, 2012 · Viewed 151.2k times · Source

I need to generate every possible combination from a given charset to a given range. Like,

charset=list(map(str,"abcdefghijklmnopqrstuvwxyz"))
range=10

And the out put should be,

[a,b,c,d..................,zzzzzzzzzy,zzzzzzzzzz]

I know I can do this using already in use libraries.But I need to know how they really works.If anyone can give me a commented code of this kind of algorithm in Python or any programming language readable,I would be very grateful.

Answer

Martijn Pieters picture Martijn Pieters · Jul 31, 2012

Use itertools.product, combined with itertools.chain to put the various lengths together:

from itertools import chain, product
def bruteforce(charset, maxlength):
    return (''.join(candidate)
        for candidate in chain.from_iterable(product(charset, repeat=i)
        for i in range(1, maxlength + 1)))

Demonstration:

>>> list(bruteforce('abcde', 2))
['a', 'b', 'c', 'd', 'e', 'aa', 'ab', 'ac', 'ad', 'ae', 'ba', 'bb', 'bc', 'bd', 'be', 'ca', 'cb', 'cc', 'cd', 'ce', 'da', 'db', 'dc', 'dd', 'de', 'ea', 'eb', 'ec', 'ed', 'ee']

This will efficiently produce progressively larger words with the input sets, up to length maxlength.

Do not attempt to produce an in-memory list of 26 characters up to length 10; instead, iterate over the results produced:

for attempt in bruteforce(string.ascii_lowercase, 10):
    # match it against your password, or whatever
    if matched:
        break