首页 > 解决方案 > 如何将多个用户名和密码作为字典添加到密码文件中?

问题描述

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 中,需要更改哪些内容,以及现有用户如何更改之前创建的密码?

标签: pythondictionaryhashpasswords

解决方案


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

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

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

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)

推荐阅读