如何在密码文件中添加多个用户名和密码作为字典?

时间:2018-11-23 02:14:47

标签: python dictionary hash passwords username

import pickle
import hashlib
import uuid

def ask_pass():
   username = input("Please create your username: ")
   password = input("Please create your password: ")

   salt = uuid.uuid4().hex
   hash_code = hashlib.sha256(salt.encode() + password.encode())

   dict = {username: {'SALT': salt,
                      'HASH': hash_code.hexdigest()
                      }
           }

    input_user=open("file.txt", "wb")
    pickle.dump(dict, input_user)

我想向file.txt中添加多个用户,但是每次创建新的用户名和密码时,我的代码都会删除存储的file.txt中的先前用户名和密码。要使每个用户信息都将其存储在file.txt中,需要进行哪些更改?现有用户如何更改之前创建的密码?

1 个答案:

答案 0 :(得分:0)

您每次保存文件时都会覆盖它,从而丢失了先前的信息。

您需要检查它是否存在,如果是这种情况,请打开它,阅读并添加新密钥,如果不存在,则创建一个新密钥。检查下面的代码。

此外,您应该谨慎使用open(可以使用withclose,如here所述)。

import os
import pickle
import hashlib
import uuid

def ask_pass():

    if os.path.isfile("file.txt"):
        with open("file.txt", "rb") as fp:
            dict = pickle.load(fp)
    else:
        dict = {}
    username = input("Please create your username: ")
    password = input("Please create your password: ")

    salt = uuid.uuid4().hex
    hash_code = hashlib.sha256(salt.encode() + password.encode())

    dict[username] ={'SALT': salt,
                     'HASH': hash_code.hexdigest()
                     }

    with open("file.txt", "wb") as fp:
        pickle.dump(dict, fp)
相关问题