0

Since I started CS50 back in 2016, I didn't implement the C version of "crack"; and now I'm in some trouble. I have written this giant for-loop structure iterating each element in the 4-character password and passing different segments of it to crypt(), but when I ran it I received no result from CS50 IDE. The cause is confirmed: after iterating through all possibilities the program was still not able to find the correct password. This means there's a logical flaw in my code, but I cannot seem to find it.

Here's the code:

import sys
import crypt
import itertools
def main():
    try:
        hashedPassword = sys.argv[1]
    except:
        if ValueError or len(sys.argv) != 2:
            print("Usage: python crack.py [Hashed Password]")
            exit(1)
    password = ['A', 'A', 'A', 'A']
    salt = hashedPassword[:2]

for index in range(4):
    for i in itertools.chain(range(65, 91), range(97,123)):
        password[0] = chr(i)
        if index > 0:
            for j in itertools.chain(range(65, 91), range(97,123)):
                password[1] = chr(j)
                if index > 1:
                    for k in itertools.chain(range(65, 91), range(97,123)):
                        password[2] = chr(k)
                        if index > 2:
                            for l in itertools.chain(range(65, 91), range(97,123)):
                                password[3] = chr(l)
                                if crypt.crypt(salt, str(password[:index])) == hashedPassword:
                                    print(''.join(password[:index]))
                                    exit(0)
                        else:
                            if crypt.crypt(salt, str(password[:index])) == hashedPassword:
                                print(''.join(password[:index]))
                                exit(0)        
                else:
                    if crypt.crypt(salt, str(password[:index])) == hashedPassword:
                        print(''.join(password[:index]))
                        exit(0)
        else:
            if crypt.crypt(salt, str(password[:index])) == hashedPassword:
                print(''.join(password[:index]))
                exit(0)

if __name__ == "__main__":
    main()

I would truly appreciate it if anyone could spot the culprit!

1 Answer 1

1

HAHAHA so I figured out what was wrong. There were multiple issues with this code, but the culprit was that I reversed the order of arguments that were passed into the crypt function; the correct function call should have been crypt.crypt(key, salt). Other issues include: 1)using str() does not convert list to string; ''.join() must be used instead 2)"crypt.crypt(salt, str(password[:index]))" is not correct, because index starts from 0 and would lag behind the actual segment of the list that I wanted to pass in. 50cI2vYkF0YU2!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .