如何比较文本文件的内容与一组输入的内容

时间:2018-03-15 11:57:39

标签: python text-files login-script

所以我正在尝试创建一个允许用户使用学校项目的用户名和密码登录的程序。但是,我的老师(他允许我向FYI提出要求)希望我们想办法让它变得安全。

所以我的思考过程是我允许用户创建登录并将用户名和密码存储在记事本文件中。为了使这些安全,我决定使用hash()函数,以便即使访问文本文件也无法看到用户名和密码。我遇到的问题是,我无法弄清楚如何让程序在文本文件中查看已保存的用户名和密码的哈希版本,然后将其与输入进行比较,以便在不打印哈希值的情况下进行。或将它们保存为变量。

我不能这样做,因为如果我在登录文件中保存了多个登录,我就不能将所有散列登录保存为一个变量。

如果有人能提供帮助,我们将不胜感激

import sys
import time

print ("welcome to this quiz.")


account = input ("first off do you have a account already. please enter yes or no only").lower


if account == no:
    account_create = input ("to continue with this quiz you need a password would you like to create a account. please enter yes or no only").lower
    if account_create == no:
        print (" the program will close in 30 seconds. if you change your mind come back and make an account")
        time.sleep(30)
        sys.exit
    else:
        print ("thank you for creating an account")

        username = input ("first off you need a username. please enter a username. be carefull once it is chasen it cant be changed")
        # need to add a function that searches the login file and compares no username is repeated
        password = input ("secondly you need a password. please choose a password. be carefull you can change it later but you will need the current one to do this.")

        username = hash(username)
         password = hash(password)

         file = open("Login.txt","w")
         file.write (username)
         file.write (",")
         file.write (password)
         file.write("\n")
         file.close()

print ("Your login details have been saved. ")
        print ("now please login")

else:

    login? = input ("would you like to login to the program").lower
    if login? == no:
        print ("please come back another time")
        time.sleep(20)
        sys.exit
    else:
        username_check = input ("please enter your username")
        password_check = input ("please enter your username")

        username_check = hash(username_check)
        password_check = hash(password_check)

        file = open("Login.txt","r")
        if username_check == 

1 个答案:

答案 0 :(得分:0)

将文件加载为将用户名(或其哈希值)映射到密码哈希值的字典。

您可以遍历文件并将每行加载到字典中。

然而,这将有点脆弱。如果某个用户希望在其用户名中包含空格或逗号,该怎么办?更好更简单的方法是使用库来序列化和反序列化字典。 python中使用的常见内容是pickle,或者如果您希望数据仍然具有人类可读性json