如何将多个用户名和密码作为字典添加到密码文件中?
How to add multiple username and password as dictionary to the password file?
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 中,现有用户如何更改之前创建的密码?
您每次保存文件时都覆盖了文件,丢失了之前的信息。
您需要检查它是否存在,如果是这样,请打开它,阅读它并向其中添加新密钥,如果不存在,则创建一个新密钥。检查下面的代码。
此外,使用open
需谨慎(如所述,可使用with
或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)
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 中,现有用户如何更改之前创建的密码?
您每次保存文件时都覆盖了文件,丢失了之前的信息。
您需要检查它是否存在,如果是这样,请打开它,阅读它并向其中添加新密钥,如果不存在,则创建一个新密钥。检查下面的代码。
此外,使用open
需谨慎(如with
或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)