python - 如何手动使用 make_password 和 check_password?

标签 python django

我尝试手动使用 make_passwordcheck_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 帮我做这件事。

最佳答案

您需要使用 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密码将无限期地存储在日志和浏览器历史记录中。

关于python - 如何手动使用 make_password 和 check_password?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29192340/

相关文章:

python - 如何覆盖 django.contrib.gis

python - Django Admin 文件上传时出现 "Connection Reset"错误

python - 添加要设置的列表

Python类实例在新线程中启动方法

python - Django 表单中的 FilterSelectMultiple 不保存

python - 使用 Python3/mysqlclient 检索以 latin1 编码的数据时的字符编码问题

python - 使用 Django Admin 上传文件

python - 如何在 python matplotlib colormap 中增加颜色分辨率

python - 子类没有正确地从父类(super class)继承结构

python - pymongo geo2d 聚合结果以什么单位返回