使用hashlib方法将明文加密后,重新验证密码时无法匹配

写django后端时使用hashlib将明文加密,为什么对于同一个密码,加密后的字符与存储在数据库的字符无法匹配
这是加密代码

def set_password(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest
    return result

这是登录验证代码

def login(request):
    if request.method == "POST":
        username = request.POST.get("user_name")
        password = request.POST.get("user_pwd")

        user = QUser.objects.filter(username = username).first()
        if user:#判断用户是否存在
            print("账户存在")
            print(set_password(password))
            print(user.password)
            if set_password(password) == user.password:#判断密码是否正确
                print("密码正确")
                response = HttpResponseRedirect("/index/")
                print("运行到了这里")
                response.set_cookie("username", user.username)
                return response
    return render(request,"bootstrap_login.html")

下图是对数据库中存储的两个帐号进行测试,代码显示加密后的字符是不一样。密码都是123456


            print(set_password(password))
            print(user.password)

img


有没有老哥会这个问题,麻烦帮我解答一下。谢谢了!!

“Devil组”引证GPT后的撰写:
问题出在set_password函数中,返回值应该是md5.hexdigest()而不是md5.hexdigest,因为hexdigest是一个方法而不是一个属性。

因此,你的set_password函数应该像这样:

def set_password(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result


修复后,应该能够得到正确的密码匹配。