3

Expected result:

The program takes a hashed password as input; this is passed to the decrypt function. The function iterates over every mixed-case n-letter combination, hashing each such string. If it finds a match to the input, it prints out the un-hashed password ; otherwise, it exits.

Actual result:

Function iterates over every mixed-case letter only for last letter in current iteration.

Description of the problem:

I'm trying to implement a simple brute-force DES-crypted password-cracker in Python. I did an implementation for 4-character passwords using a lot of for loops, but now I want to refactor it for a range of lengths, using recursion. How can I iterate over every character combination, starting from 1-char combination up to 4-character string combination?

I wanted to use this line:

            password[i] = string.ascii_letters[j]

But I get this error:

TypeError: 'str' object does not support item assignment

Code snippet:

def decrypt(encryptedText):
    # reference global variable
    global password
    # check curr password guess length
    pwdlen = len(password)

    if pwdlen >= 4:
        print("Password is longer than 4 characters, exiting...")
        exit(2)

    # debug lines
    print("password is {}".format(password))
    print("length: {}".format(pwdlen))
    time.sleep(2)

    # first two characters is salt
    salt = encryptedText[:2]

    # Check hashes for every combination of strings and compare them
    # starts with last char
    for i in range(pwdlen, 0, -1):
        for j in range(0, len(string.ascii_letters)):
            password = string.ascii_letters[:pwdlen] + string.ascii_letters[j]
            hashed = crypt.crypt(password, salt)

            # debug line
            print(password)

            # if found - print password and exit
            if hashed == encryptedText:
                print(password)
                exit(0)

    # this makes recursion go through +1 char combinations on every iteration
    password = (pwdlen + 1) * 'a'

    return decrypt(encryptedText)
Prune
  • 76,765
  • 14
  • 60
  • 81
Rupcio
  • 57
  • 6

1 Answers1

6

Strings are immutable. You can't assign a new value to part of the string. Instead, you have to build a new value and assign that to the original variable. For instance:

# password[i] = string.ascii_letters[j]
password = password[:i] + string.ascii_letters[j] + password[i+1:]

Second, you can probably do much better by using the itertools package to generate all of the permutations you want. For instance, generate the product of asci_letters as many times as you want, and step through the join of those letter sequences.

Prune
  • 76,765
  • 14
  • 60
  • 81