Python generates all possible strings of length n

I am studying an ethical hacker. I have a password hash and a crypt algorithm (sha256 / sha512). I want to parse all lines from a file and check if the password hash matches the hash of each line from the file.

The generated string can contain small letters, uppercase letters, and numbers.

Any ideas on how to generate all possible strings of length n that can contain letters and numbers?

+5


source to share


3 answers


Here is a piece of code that [Python 3.Docs] uses: itertools. product (* repeats, repeat = 1) . Note that the number of lines generated is , so for testing purposes use small values for the length:
62 ** length



import string
import itertools


def generate_strings(length=3):
    chars = string.ascii_letters + string.digits  # "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    for item in itertools.product(chars, repeat=length):
        yield "".join(item)

      

+7


source


You can use itertools.product

:

print([''.join(x) for x in itertools.product('abcABC123', repeat=3)])
['aaa',
 'aab',
 'aac',
 'aaA',
 'aaB',
 'aaC',
 'aa1',
 'aa2',
 'aa3',
 'aba',
...

      



Just add the remaining characters to the input line. You can use constants from the module strings

for this.

Remember this is growing rapidly.;)

+3


source


Use itertools.product

from itertools import product
from string import ascii_letters, digits

for i in product(ascii_letters + digits, repeat=n):
    print(''.join(i))

      

+2


source







All Articles