Django中保存密码到数据库前的最佳哈希方法

4 投票
2 回答
1492 浏览
提问于 2025-04-17 10:17
def register(request):
    flag = True
    possible = '0123456789abcdefghijklmnopqrstuvwxyz'
    token = ''

    current_datetime = datetime.datetime.now()

    user = UsersModelForm()
    if request.method == 'POST':
        userf = UsersModelForm(request.POST)
        username = userf.data['username']
        password = userf.data['password']
        passwordrepeat = userf.data['passwordrepeat']
        email = userf.data['email']

        if password != passwordrepeat:
            flag = False
            passVariable = {'user':user, 'flag': False}
            return render_to_response('register.html', passVariable, context_instance=RequestContext(request))

        elif password == passwordrepeat:
            for i in range(1,10):
                temp = random.choice(possible)
                token = token + temp

            print token
            if userf.is_valid():
                check = userf.save(commit=False)
                check.email_token = token
                check.email_token_expiry = current_datetime + timedelta(1)
                check.save()
                return HttpResponseRedirect('/')
    else:
        return render_to_response('register.html', {"user": user, 'flag': True}, context_instance=RequestContext(request))

我需要在把 userf.data['password']userf.data['repeatpassword'] 保存到数据库之前,先对它们进行加密处理。

请问在用Python进行加密时,哪种加密方法比较好呢?

2 个回答

1

你可以在这里找到关于如何处理这个问题的解释,特别是针对 django.contrib.auth 的部分,链接在这里。如果你想了解更详细的信息,可以查看 make_password 函数,它在hashers模块中。

6

使用 bcrypt

下面是一个从 README 中摘录的例子:

import bcrypt

# Hash a password for the first time
hashed = bcrypt.hashpw(password, bcrypt.gensalt())

# gensalt's log_rounds parameter determines the complexity
# the work factor is 2**log_rounds, and the default is 12
hashed = bcrypt.hashpw(password, bcrypt.gensalt(10))

# Check that an unencrypted password matches one that has
# previously been hashed
if bcrypt.hashpw(plaintext, hashed) == hashed:
    print "It matches"
else:
    print "It does not match"

撰写回答