7

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?

John P
  • 1,159
  • 2
  • 18
  • 44
  • 1
    [`itertools.product`](https://docs.python.org/2/library/itertools.html#itertools.product) (with `repeat=n`) might come in handy. – CristiFati Mar 30 '17 at 13:54
  • it's not duplicate as there are no digits included – John P Mar 30 '17 at 14:09
  • 1
    There's no structural difference. You just need to extend the alphabet. – languitar Mar 30 '17 at 14:43
  • 1
    A better approach is to use lists of frequent passwords, see [SecLists](https://github.com/danielmiessler/SecLists/tree/master/Passwords). . – zaph Mar 30 '17 at 14:58
  • Interesting link. Anyway I want to implement by myself. Also when there are password validation rules it may be easier to generate all the possible strings and then just check them – John P Mar 30 '17 at 15:07
  • 1
    For a 8 character passwords there are about 100,000,000,000,000 possibilities. Also see: Infosec [password-cracking-tools](http://resources.infosecinstitute.com/10-popular-password-cracking-tools/) Advanced Password Recovery [hashcat](https://hashcat.net/hashcat/) – zaph Mar 30 '17 at 15:25
  • these are just permutations of chars in a set with repetitions. In the case of omitting special chars, there are 52^8 posibilities. So I should think about improvements – John P Mar 30 '17 at 19:11

3 Answers3

9

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)
CristiFati
  • 38,250
  • 9
  • 50
  • 87
5

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. ;)

languitar
  • 6,554
  • 2
  • 37
  • 62
2

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))
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96