我正在尝试完成一个项目,在该项目中,您注册后可以创建一个密码,然后将该密码存储在一个文件中,该文件将在登录时读取(密码存储为哈希值)当用户输入用户密码已哈希被比作存储的文本。)我有问题,但是哈希密码比较存储的密码。看来无论我如何更改,两个字符串都不匹配。 (将输入的密码与存储的密码哈希进行比较的地方在第38行。)
代码:
import hashlib
login_or_signup = input("Would You like to login or signup? ")
f = open("hashed_password_list.txt", "r")
print(f.read())
#SIGNUP PHAZE---------------------------------------------------
if login_or_signup == "signup":
username = input("What is your name? ")
password_sign_up = input("Enter your desired password: ")
hash_object = hashlib.sha256(password_sign_up.encode('utf-8'))
hex_dig = hash_object.hexdigest()
#print(hex_dig)
pw2 = input("confirm password: ")
hash_object = hashlib.sha256(pw2.encode('utf-8'))
hex_dig2 = hash_object.hexdigest()
#print(hex_dig2)
if hex_dig == hex_dig2:
print("the passwords match! Thanks for creating an accout with us, " + username)
text = hex_dig
saveFile = open('hashed_password_list.txt', 'w')
saveFile.write(text)
saveFile.close()
else:
print("sorry the passwords did not match.")
#LOGIN PHAZE---------------------------------------------------
elif login_or_signup == "login":
password_sign_up2 = input("Enter your password: ")
hash_object2 = hashlib.sha256(password_sign_up2.encode('utf-8'))
hex_dig2 = hash_object2.hexdigest()
#print(hex_dig)
#CHECK PASSWORD---------------------------------------------
if f == hex_dig2:
#print(info)
print("succesfully logged in! ")
f.close()
else:
print("The password you entered did not match our database please create an account")
#IF USER ENTERS WRONG COMMAND AT BEGINNING----------------------
else:
print("error!")
答案 0 :(得分:0)
鉴于:
f = open("hashed_password_list.txt", "r")
print(f.read())
比较:
if f == hex_dig2:
是错误的,因为您正在将open
的返回值(即文件对象)与字符串hex_dig2
进行比较。
这就是您想要的:
if f.read() == hex_dig2:
但是请记住注释掉行print(f.read())
,否则第一次读取将占用文件内容。
由于这只是用例的起点,因此请考虑使用with statement来管理文件资源,例如:
with open("hashed_password_list.txt", "r") as f:
if f.read() == hex_dig2:
print(info)
print("Successfully logged in! ")
else:
print("The password you entered did not match our database please create an account")