您的位置:首页 > 编程语言 > Go语言

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

2017-02-17 15:08 357 查看
在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐