Recursively repeating each combination of characters

Expected Result:

The program accepts a hashed password as input; this is passed to the decryption function. The function iterates over each mixed n-letter combination, hashing each such string. If it finds a match with the input, it prints the un-hashed password; otherwise it will exit.

Actual result:

The function iterates over each letter of the mixed case for only the last letter in the current iteration.

Description of the problem:

I am trying to implement a simple password cracked password cracked in Python. I made an implementation for 4 character passwords using lots of loops, but now I want to refactor them for a range of lengths using recursion. How can I iterate over each combination of characters, starting with a combination of 1 char to a 4-character combination of strings?

I wanted to use this line:

            password[i] = string.ascii_letters[j]

      

But I am getting this error:

TypeError: 'str' object does not support item assignment

      

Snippet of code:

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)

      

+3


source to share


1 answer


Strings are immutable. You cannot assign a new value to part of a string. Instead, you need to create a new value and assign it to the original variable. For example:

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

      



Second, you can probably do much better using itertools to generate any permutations you need. For example, generate the product asci_letters as many times as you like and join these sequences of letters.

+6


source







All Articles