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

时间:2021-01-17 19:15:55

在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

之后验证成功。

当然经过这些修改后最终的安全性比起django自带的降低很多,但是需求就是这样的,必须满足。

完成需求的过程中查找了不少资料,最后还是在django文档中找到的答案,文档还是很全全面的,以后通读还是感觉有必要的。