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  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值