【问题标题】:Best hashing method before saving password into database table for django将密码保存到 django 的数据库表之前的最佳哈希方法
【发布时间】:2012-02-10 17:16:06
【问题描述】:
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 进行散列?

【问题讨论】:

    标签: python database django hash passwords


    【解决方案1】:

    使用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"
    

    【讨论】:

    • 你能贴出如何使用 bcrypt 的代码吗?那会更有帮助。
    【解决方案2】:

    您可以找到有关如何为 django.contrib.auth here 完成此操作的说明。详细信息也可以看一下hashers module中的make_password函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 2012-06-23
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多