Search code examples
pythonhashlib

Comparing 2 hash values returning False even though they are the same


How the program works is that the user sends 2 inputs over (userinput and passwordinput). These are compared against the filename of a textfile (which is the username) and the context (which is the hashed password). The passwordinput gets hashed and returns the same as the hashed original password with no diferences, however when I compare with the if statement it returns False. Here's my code:

import os
import hashlib

username = "coolcat"
password = "my secret password!!"

result = hashlib.sha1(password.encode("utf-8"))

if not os.path.exists(f"{username}.txt"):
    open(f"{username}.txt", 'w').close()
with open(f"{username}.txt", "w") as file:
   file.write(str(result.digest()))

userinput = input("Your username please : ")
passwordinput = input("Your password please : ")
resulte = hashlib.sha1(passwordinput.encode("utf-8"))
print(str(resulte.digest()))
try :
    with open(f"{userinput}.txt", "r") as file:
        hashed = file.read()
    print(hashed)

    if hashed == resulte.digest():
        print("Access Granted")
    if hashed != resulte.digest():
        print("Wrong password!!")
except FileNotFoundError :
    print("Username not found!!1!")

Solution

  • Assuming you want to compare two strings, change hashed output to a string too. other than that you are comparing bytes with string which will always return false.

    import os
    import hashlib
    
    username = "coolcat"
    password = "my secret password!!"
    
    result = hashlib.sha1(password.encode("utf-8"))
    
    if not os.path.exists(f"{username}.txt"):
        open(f"{username}.txt", 'w').close()
    with open(f"{username}.txt", "w") as file:
       file.write(str(result.digest()))
    
    userinput = input("Your username please : ")
    passwordinput = input("Your password please : ")
    resulte = hashlib.sha1(passwordinput.encode("utf-8"))
    print(str(resulte.digest()))
    try :
        with open(f"{userinput}.txt", "r") as file:
            hashed = str(file.read())
        print(str(hashed))
    
        if hashed == str(resulte.digest()):
            print("Access Granted")
        if hashed != str(resulte.digest()):
            print("Wrong password!!")
    except FileNotFoundError :
        print("Username not found!!1!")