Django 自定密碼加密方式 及自定義驗證方式

1.在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是加鹽的。

2.自定義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。

3.自定義驗證

在settings.py中加入以下:

AUTHENTICATION_BACKENDS = (  
 'chicken.mybackend.MyBackend',  
)  
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

之后驗證成功。

當然經過這些修改后最終的安全性比起django自帶的降低很多

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容