我尝试手动使用make_password
和check_password
函数。我在其中一种观点中这样做(出于测试原因):
#iteration one:
def enter(request):
res = make_password('admin')
return HttpResponse(res)
因此,当我进入enter
页面时,会看到以下内容:
pbkdf2_sha256$15000$fmX24ZPCKBdA$fvpfYMacxOi44QFDeLLfRRUN85RweMJTfxxoC+YS2XE=
假设我将此输出以以下形式存储在文本文件(同样出于测试原因)passwords.txt
中:
1 pbkdf2_sha256$15000$fmX24ZPCKBdA$fvpfYMacxOi44QFDeLLfRRUN85RweMJTfxxoC+YS2XE=
2 ....hash for another user
在第二次迭代中,我想检查我的密码(将其存储在请求变量的GET ['pass']中),但是不知道如何:
def login(request):
# How to use check_password here to check against data stored in
# passwords.txt
# it should either output False
# or an id, like 1 in our test case for password 'admin'.
我想再次强调一下,我想手动使用它,只是为了了解这些功能背后的逻辑。因此,我现在不想让Django
替我做。
python大神给出的解决方案
您需要使用django.contrib.auth.hashers.check_password
,并将未加密的密码和加密的字符串都传递给它,如果匹配则返回True
,否则返回False
。
从而
encrypted = 'pbkdf2_sha256$15000$fmX24...'
if check_password(request.POST['pass'], encrypted):
print("Login successful")
请注意,您永远不想使用GET
方法提交密码,因为使用GET
时,密码将无限期地存储在日志和浏览器历史记录中。