0

Below is a "Brute Force" word guessing...thing. I'ts to prove to my sibling how long it takes to find a password even knowing the number of characters using brute force. After letting this run for a couple hours with no success I think he gets the point. Now I want to put some logic behind it and for the life of me I can't figure it out. I've found things similar to what I want online but I don't know how to adapt it to my code.

import string
import random

def make_random():
   return''.join([random.choice(string.ascii_uppercase) for n in xrange(3)])

while True:
   random2=make_random()
   if random2 != "AAA":
      print(random2)
   if random2 == "AAA":
      print("AAA")
      print("Found")
      break

I think I need to have a variable to keep track of all the choices that have been guessed and compare that to the new string and set them so they can't equal but I honestly don't know.

Any help is good help.

Craig Walker
  • 131
  • 2
  • 10

2 Answers2

3

If somebody is going to systematically try all different passwords, then he needs to iterate through all possible combinations, without trying the same combination twice. Here is one way to do that in Python:

import itertools
import string

real_pass = 'AAC'


def find_num_iterations_to_guess_password(pass_length):
    all_letters = string.ascii_uppercase
    iterations = 0
    for i in itertools.product(all_letters, repeat=pass_length):
        guess = ''.join(i)
        if guess == real_pass:
            print(f'the real password is {guess} and was guessed after {iterations}')
            break
        iterations += 1


find_num_iterations_to_guess_password(len(real_pass))
giliev
  • 2,938
  • 4
  • 27
  • 47
  • Thanks this worked. The only other thing that I ended up adding was another if statement so we could watch the program guess. `if guess != real_pass:` `print(guess)` – Craig Walker Nov 30 '18 at 17:19
0

A better option than randomly generating guesses and comparing against a list of already used choices is to algorithmically create all possible n-length products and iterate over them:

from itertools import product
import string

for i in product(string.ascii_uppercase, repeat=3):
    if ''.join(i) == 'AAA':
        print("Found")
        break

Edit: Use product, not permutation

Tim
  • 2,756
  • 1
  • 15
  • 31