Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python generate all possible strings of length n [duplicate]

Tags:

python

I am learning ethical hacking. I have the hash key of a password and the crypt algorithm (sha256/sha512). I want to parse all the strings from a file and to check if the hash of the password matches the hash of each of the string from the file.

The generated String may contain small letters, big letters and numbers.

Any ideas how to generate all the possible Strings of length n which may contain letters and numbers?

like image 845
Andrew T Avatar asked Mar 30 '17 13:03

Andrew T


People also ask

How do you find the length of a multiple string in Python?

Python len() Function len() is a built-in function in python. You can use the len() to get the length of the given string, array, list, tuple, dictionary, etc.

How many string of length n can be formed from the English alphabet?

Explanation: There are 5 vowels and 21 consonants in English alphabets. So for vowel 'a' we can have 42 strings of the form 'ab', 'ba', 'ac', 'ca', 'ad', 'da' and so on. For the other 4 vowels, the same process repeats, and we get a total of 210 such strings.


2 Answers

Here's a piece of code that uses [Python 3.Docs]: itertools.product(*iterables, repeat=1).
Note that the number of generated strings is 62 ** length, so for testing purposes use small values for 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)
like image 145
CristiFati Avatar answered Oct 21 '22 05:10

CristiFati


You could 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 you need to the input string. You can use the constants from the strings module for this.

Be aware that this quickly grows. ;)

like image 26
languitar Avatar answered Oct 21 '22 05:10

languitar