比较 2 个哈希值返回 False,即使它们相同

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

该程序的工作原理是用户发送 2 个输入(用户输入和密码输入)。 这些将与文本文件的文件名(即用户名)和上下文(即散列密码)进行比较。密码输入被散列并且 returns 与散列的原始密码相同,没有差异,但是当我与 if 语句比较时它 returns 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 = 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!")

你在这里用 str 来打印东西是在自欺欺人。问题是 hash 是 Unicode 字符串,而 resulte.digest() 是字节字符串。它们都 PRINT 相同,因为您使用了 str 函数来转换它们。如果你有字节字符串 b'abc',它包含三个字节,你调用 str(b'abc'),你会得到一个 Unicode 字符串 b'abc',但它包含 6 个字符:b 引号在里面。这就是区别。您编写的文件是一个包含 Unicode 字符串的 Unicode 文件,该字符串以文字字符 "b'".

开头

解决办法是以二进制模式打开文件:

import os
import hashlib

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

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

with open(f"{username}.txt", "wb") as file:
   file.write(result.digest())

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

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

假设您要比较两个字符串,也将散列输出更改为字符串。除此之外,您正在将字节与字符串进行比较,该字符串始终 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!")