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



程序的工作原理是用户发送2个输入(userinput和passwordinput(。将它们与文本文件的文件名(即用户名(和上下文(即散列密码(进行比较。passwordinput经过散列处理,并返回与散列后的原始密码相同的密码,没有任何区别,但当我与if语句进行比较时,它返回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()是字节字符串。它们都打印相同,因为您使用了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!")

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

最新更新