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自带的降低很多

你可能感兴趣的:(Django 自定密码加密方式 及自定义验证方式)