登录系统 - 从文件中读取并比较值以允许或拒绝进入系统



我正在设计一个登录系统。我已经完成了密码的哈希处理,我希望python从文件中读取并将用户输入的值与文件中的值进行比较,如果它们匹配,那么用户可以进入系统。

这是我的代码:

username = input("Enter your username: ")
password = input("Enter your password: ")
#hashing
p = len(password)+3
hashValue = 0
for element in password:
    hashValue += ord(element)*(37**(p*3+2))
    p += 1
#file reading
searchfile = open("users.txt","r")
for line in searchfile:
    if username in line:
        print(line)
        passwordFile = searchfile.readline()
        print(passwordFile)
        if password == passwordFile:
            print("Succesfully logged in.")
        else:
            print("Denied.")

这是文件的内容:

user1
5682064547402171341935718587051072007223952507159509922486300727280224437681256157289392848984758601859653014989196589
user2
5459242799619652684746638604361187538149455998072046842553294309854609933784480688770064676790163754304952120716010653

第一个哈希值 = 密码123第二个哈希值 = 密码321

我认为这里的问题是,当python读取下一行时,它会用空格()读取它,这就是为什么当它将其与输入的值进行比较时,它不起作用。我不知道如何避免阅读它。请帮忙。

我也尝试将文件中的值放入字典中,但这也不起作用。

upD = {}
with open ("users.txt") as f:
    for line in f:
        (key,val) = line.split()
        upD[key] = val
        print(upD)
        if password in upD[username]:
            print("Welcome.")
        else:
            print("Denied.")

当我尝试这样做时,我像这样存储文件的内容:

user1   5682064547402171341935718587051072007223952507159509922486300727280224437681256157289392848984758601859653014989196589
user2   5459242799619652684746638604361187538149455998072046842553294309854609933784480688770064676790163754304952120716010653

如果有其他方法,请告诉我。谢谢。

1)您不能将文件迭代(for line in searchfile)与其他形式的文件访问(searchfile.readline())混合使用。请尝试passwordFile = next(searchfile)

2) 您正在将明文password变量与users.txt文件中的哈希进行比较。请尝试if hashValue == int(passwordFile)

username = input("Enter your username: ")
password = input("Enter your password: ")
#hashing
p = len(password)+3
hashValue = 0
for element in password:
    hashValue += ord(element)*(37**(p*3+2))
    p += 1
#file reading
searchfile = open("users.txt","r")
for line in searchfile:
    if username in line:
        print(line)
        passwordFile = next(searchfile)
        if hashValue == int(passwordFile):
            print("Succesfully logged in.")
        else:
            print("Denied.")

相关内容

最新更新