【问题标题】:Django change hasher algorithm for user passwordDjango更改用户密码的哈希算法
【发布时间】:2021-08-19 08:15:21
【问题描述】:

我需要将 SHA512 密码从另一个数据库传输到 Dango。

示例密码 - b792e3c67205a800d16fceb2dacf5b70fada6f31e905352750e093bedc95ab970c0121f7c3f2a3bfcab32f3cb8a2c0d2273ada96b082dd0fbd012dbae379dcb1

我需要使用此密码进行身份验证

我试试这个。但它不起作用

hasher.py

import hashlib

from django.contrib.auth.hashers import BasePasswordHasher, mask_hash
from django.utils.crypto import constant_time_compare
from django.utils.translation import gettext_noop as _


class CustomPasswordHasher(BasePasswordHasher):

    algorithm = 'sha512'

    def salt(self):
        return ''

    def encode(self, password, salt):
        hash = hashlib.sha512(password.encode())
        return hash

    def verify(self, password, encoded):
        encoded_2 = self.encode(password, '')
        return constant_time_compare(encoded, encoded_2)

    def safe_summary(self, encoded):
        return {
            _('algorithm'): self.algorithm,
            _('hash'): mask_hash(encoded, show=3),
        }

settings.py

PASSWORD_HASHERS = [
    'restorating.hasher.CustomPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

【问题讨论】:

    标签: django django-authentication hashlib


    【解决方案1】:

    原来如此!

    但哈希以

    格式存储
    import hashlib
    
    from django.contrib.auth.hashers import BasePasswordHasher
    from django.utils.crypto import constant_time_compare
    
    
    class CustomPasswordHasher(BasePasswordHasher):
        algorithm = 'sha512'
    
        def encode(self, password, salt):
            assert password is not None
            hash = hashlib.sha512(password.encode()).hexdigest()[:120]
            return '%s$%s' % (self.algorithm, hash)
    
        def verify(self, password, encoded):
            encoded_2 = self.encode(password, '')
            return constant_time_compare(encoded, encoded_2)
    

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 1970-01-01
      • 2020-09-16
      • 2012-05-24
      • 2011-06-18
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多