简体   繁体   中英

How to enumerate a string using only loops or recursion? (For password cracking example)

I know there are already some answers here. But see my code what i wanna do.

genpass = ''

#This is the password that we want to crack.

psd = 'feed'

#This is characters set that is minimised to speed up the problem

characters = {'a','b','c','d','e','f','g','h'}

def brute_force(psd, chr, genpass):
    # this function generates password
    # and check if this is match to psd or not.
   if genpass == psd:
       print('password found!', genpass)

If you cannot use built in combitorial functions, recursion is the way to go.

This Python Guru article is a great place to start for understanding the oddities of recursion

For this particular example, lets make a function that just worries about changing one index of our password

def rotate_char(guess, i):
    for c in characters:
        guess[i] = c

There we go, this function will loop through all characters in a single index.

Now we can call it again with the next index recursively modify all indecies.

def rotate_char_recursive(guess, i):
    global answer
    for c in characters:
        guess[i] = c
        rotate_char_recursive(guess, i+1) # call again with next index

However if we run this we will get an error as i gets too large. What we need is a terminating condition.

def rotate_char_recursive(guess, i):
    global answer
    for c in characters:
        guess[i] = c
        if "".join(guess) == psd:  # Our check to end recursion
            answer = guess
            return
        if i < len(guess) -1:
            rotate_char(guess, i+1)  # call again with next index
            if len(answer) > 0:  # In case we find the result
                return answer

Now, to call our recursive function:

psd = 'feed'
characters = {'a','b','c','d','e','f','g','h'}
guess = ['a']
answer = []

#Recerusive character rotation
def rotate_char_recursive(guess, i):
    global answer
    for c in characters:
        guess[i] = c
        if "".join(guess) == psd:  # Our check to end recursion
            answer = guess
            return
        if i < len(guess) -1:
            rotate_char_recursive(guess, i+1)  # call again with next index
            if len(answer) > 0:  # In case we find the result
                return answer


while len(guess) < 20:  # Safety catch, in case we do not find the password
    result = rotate_char_recursive(guess, 0)
    if result:
        break
    guess += 'a'  # if password is not found, try a longer password

print(result) # ['f', 'e', 'e', 'd']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM