-2

I've made a brute force password cracker which works, but I also made a string combining generator which would be better as the brute force string generator; however I can't figure out how to combine the two.

Brute force code:

import random

characters = "ABCDE"
length = 5
while True:
    pw = ""

   #Generating Section
    for i in range(length):
        next_index = random.randrange(len(characters))
        pw = pw + characters[next_index]

    if pw == "ABCDE":
        print()
        print()
        print("Password acquired.")
        break

Character generator code:

import itertools

res = itertools.permutations(test ,length)
for i in res: 
    print(''.join(i))

I would like to replace the "Generating" section from the brute force code with the improved generator code but I can't do this. Please help.

David Greydanus
  • 2,551
  • 1
  • 23
  • 42
Hoxephos
  • 71
  • 1
  • 1
  • 6

3 Answers3

1

I changed your code to use itertools and to iterate through the possible passwords using a generator so you aren't computing more than needed.

import itertools

characters = "ABCDE"
length = 5
done = False

while True:
    def pw_guess():
        res = itertools.permutations('ABCDE' ,5)
        for guess in res:
            yield guess

    #Make generator object
    guess_generator = pw_guess()

    for guess in guess_generator:
         if guess == ('A', 'B', 'C', 'D', 'E'):
            print()
            print("Password acquired: " + str(guess))
            done = True
            break
    if done:
        break

A generator computes the guesses one by one as opposed to computing in advance.

user4157124
  • 2,809
  • 13
  • 27
  • 42
David Greydanus
  • 2,551
  • 1
  • 23
  • 42
0

Tbh, I've made a brute force program which doesn't require as much code. Some of the lines in my code are optional (like counting how many attempts it took to guess the password.). Try my code:

import random
import string
guessAttempts = 0
myPassword = input("Enter a password for the computer to try and guess: ")
passwordLength = len(myPassword)
while True:
    guessAttempts = guessAttempts + 1
    passwordGuess = ''.join([random.choice(string.ascii_letters + string.digits)for n in range(passwordLength)])
    print(passwordGuess)
    if passwordGuess == myPassword:
        print("Password guessed successfully!")
        print("It took the computer %s guesses to guess your password." % (guessAttempts))
        break
0

I used itertools.product to generate any length of passwords from the list of [a-z, 0-9]. 1800 in the last loop is for my testing.

import itertools
char_set = [chr(_) for _ in list(range(ord('a'), ord('z')+1))] + [chr(_) for _ in list(range(ord('0'), ord('9')+1))]

def my_fun(alphanum):
    i = 0
    while True:
        result = itertools.product(alphanum, repeat=i)
        for guess in result:
            yield guess
        i += 1

g = my_fun(char_set)
for c in range(1800):
        print((''.join(next(g))))