【发布时间】:2021-12-22 23:48:11
【问题描述】:
程序的工作原理是用户发送 2 个输入(用户输入和密码输入)。
这些将与文本文件的文件名(即用户名)和上下文(即散列密码)进行比较。密码输入被散列并返回与散列后的原始密码相同,没有差异,但是当我与 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!")
【问题讨论】:
-
我建议你打印你比较的参数的类型......这可能会给你答案
-
hashed == resulte.digest()你将字符串与字节进行比较,这将始终是False -
不确定,但尝试查看从文件读取时是否没有收到
\n。 -
一些旁注:不需要
if not os.path.exists部分 - 当使用'w'打开文件时,如果文件不存在,则会创建该文件。您可以将整个if hashed != resulte.digest():行替换为简单的else:... -
谢谢!!将 resulte.digest() 包裹在 str 周围是有效的。