Dictionary attack on SHA1 hash

1.4k Views Asked by At

The following is my code. I have been trying to fix the code to perform dictionary attack on a hash (SHA-1) and I am getting the following result. P.S. I am a beginner to coding.

import hashlib
import random
#plug in the hash that needs to be cracked
hash_to_crack = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
#direct the location of the dictionary file
dict_file = "C:/Users/kiran/AppData/Local/Programs/Python/Python37/dictionary.txt"

def main():
    with open(dict_file) as fileobj:
        for line in fileobj:
            line = line.strip()
            if hashlib.sha1(line.encode()).hexdigest() == hash_to_crack:
                print ("The password is %s") % (line);
                return ""
    print ("Failed to crack the hash!")
    return ""


if __name__ == "__main__":
    main()

The result:

RESTART: C:/Users/kiran/AppData/Local/Programs/Python/Python37/Codes/datest1.py
The password is %s
Traceback (most recent call last):
  File "C:/Users/kiran/AppData/Local/Programs/Python/Python37/Codes/datest1.py", line 20, in <module>
    main()
  File "C:/Users/kiran/AppData/Local/Programs/Python/Python37/Codes/datest1.py", line 13, in main
    print ("The password is %s") % (line);
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'
2

There are 2 best solutions below

1
On BEST ANSWER

This line is not valid python3 syntax: (EDIT: it's a valid syntax ! But not what you want :) )

print ("The password is %s") % (line);

Use this instead:

print ("The password is %s" % line)

Also, accordig to the error message, line might be None.

0
On

You're using Python 3, where print is a function. The line:

print ("The password is %s") % (line)

calls the function print with the argument "The password is %s". The function returns None. Then None % (line) gives the error message you see.

Most idiomatic is to write the line this way instead:

print("The password is", line)

Other ways that would work:

print("The password is %s" % line)
print(("The password is %s") % (line))