2016-04-22 54 views
0

我正在设计一个登录系统。我已经完成了对密码的哈希处理,我希望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 

第一散列值= password123 第二散列值= password321

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

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

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 

如果没有这样做,请让我知道的另一种方式。谢谢。

回答

0

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.") 
+0

WORKS!非常感谢你! – FirkaPirka