python - 如何将多个用户名和密码作为字典添加到密码文件中?
问题描述
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
or ,如此处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)
推荐阅读
- html - 如何将颜色渐变应用到 .SVG 图像?
- android - 应用内结算的 Android 开发者通知
- r - 根据条件子集中的行号编辑 data.table 列
- javascript - 在数组中添加星号?
- regex - 如何在 Sublime 3 中以连续的方式在许多相关文件上自动增加/添加/重新编号?
- android - PC 崩溃后 Android Studio 出现错误
- java - 设置属性“java.io.tmpdir”会导致测试失败
- ruby-on-rails - Rails 脚手架关联 has_many 错误:1 个错误禁止保存此产品
- php - 我的代码有什么问题?我在调用未定义的方法 mysqli::error() 时出错
- php - 尝试使用 ErrorDocument 处理请求时遇到 403 禁止错误。PHP 声音