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  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM