• django 自定义 密码加密方式 及自定义验证方式


    在django1.6中,默认的加密方式是pbkdf_sha256,具体算法不表,一直以来用django的自带用户验证都十分顺手,但如果需要修改默认加密方式为md5,具体方法为:

    在settings.py中加入:

    PASSWORD_HASHERS = (  
      
        'myproject.hashers.MyMD5PasswordHasher',  
        'django.contrib.auth.hashers.MD5PasswordHasher',  
        'django.contrib.auth.hashers.PBKDF2PasswordHasher',  
        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',  
        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',  
        'django.contrib.auth.hashers.BCryptPasswordHasher',  
        'django.contrib.auth.hashers.SHA1PasswordHasher',  
        'django.contrib.auth.hashers.CryptPasswordHasher',  
    )  
    

    django会默认使用第一条加密方式。

    这个是我自定义的加密方式,就是基本的md5,而django的MD5PasswordHasher是加盐的。

    以下是我的自定义hashers.py:

    from django.contrib.auth.hashers import BasePasswordHasher,MD5PasswordHasher  
    from django.contrib.auth.hashers import mask_hash  
    import hashlib  
      
    class MyMD5PasswordHasher(MD5PasswordHasher):  
        algorithm = "mymd5"  
      
        def encode(self, password, salt):  
            assert password is not None  
            hash = hashlib.md5(password).hexdigest().upper()  
            return hash  
      
        def verify(self, password, encoded):  
            encoded_2 = self.encode(password, '')  
            return encoded.upper() == encoded_2.upper()  
      
        def safe_summary(self, encoded):  
            return OrderedDict([  
                    (_('algorithm'), algorithm),  
                    (_('salt'), ''),  
                    (_('hash'), mask_hash(hash)),  
                    ])  
    

    然而仅仅修改这些,在配合django的authenticate验证时无法进行。

    经过一些查找,发现需要在自定义authenticate。以下为方法:

    在settings.py中加入以下:

    AUTHENTICATION_BACKENDS = (  
        'chicken.mybackend.MyBackend',  
    )  
    

    以下代码为自定义的mybackend.py:

    import hashlib  
    from pro import models  
      
    class MyBackend(object):  
        def authenticate(self, username=None, password=None):  
            try:  
                user = models.M_User.objects.get(username=username)  
                print user  
            except Exception:  
                print 'no user'  
                return None  
            if hashlib.md5(password).hexdigest().upper() == user.password:  
                return user  
            return None  
      
        def get_user(self, user_id):  
            try:  
                return models.M_User.objects.get(id=user_id)  
            except Exception:  
                return None  
    
  • 相关阅读:
    数组里的数据绑定到dataset中
    有关字符串匹配的方法
    sql语句全集
    Dialog 的6中提示方式
    android开源项目和框架
    MyEclipse DB Browser使用图文全攻略
    省市县联动(转)
    LRU算法
    Java 性能优化小细节
    HashMap
  • 原文地址:https://www.cnblogs.com/ccorz/p/django-zi-ding-yi-mi-ma-jia-mi-fang-shi-ji-zi-ding.html
Copyright © 2020-2023  润新知