Django密码存储策略分析
作者:蓝绿色~菠菜 发布时间:2022-03-10 04:16:33
一、源码分析
Django 发布的 1.4 版本中包含了一些安全方面的重要提升。其中一个是使用 PBKDF2 密码加密算法代替了 SHA1 。另外一个特性是你可以添加自己的密码加密方法。
Django 会使用你提供的第一个密码加密方法(在你的 setting.py 文件里要至少有一个方法)
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
]
我们先一睹自带的PBKDF2PasswordHasher加密方式。
class BasePasswordHasher(object):
"""
Abstract base class for password hashers
When creating your own hasher, you need to override algorithm,
verify(), encode() and safe_summary().
PasswordHasher objects are immutable.
"""
algorithm = None
library = None
def _load_library(self):
if self.library is not None:
if isinstance(self.library, (tuple, list)):
name, mod_path = self.library
else:
name = mod_path = self.library
try:
module = importlib.import_module(mod_path)
except ImportError:
raise ValueError("Couldn't load %s password algorithm "
"library" % name)
return module
raise ValueError("Hasher '%s' doesn't specify a library attribute" %
self.__class__)
def salt(self):
"""
Generates a cryptographically secure nonce salt in ascii
"""
return get_random_string()
def verify(self, password, encoded):
"""
Checks if the given password is correct
"""
raise NotImplementedError()
def encode(self, password, salt):
"""
Creates an encoded database value
The result is normally formatted as "algorithm$salt$hash" and
must be fewer than 128 characters.
"""
raise NotImplementedError()
def safe_summary(self, encoded):
"""
Returns a summary of safe values
The result is a dictionary and will be used where the password field
must be displayed to construct a safe representation of the password.
"""
raise NotImplementedError()
class PBKDF2PasswordHasher(BasePasswordHasher):
"""
Secure password hashing using the PBKDF2 algorithm (recommended)
Configured to use PBKDF2 + HMAC + SHA256.
The result is a 64 byte binary string. Iterations may be changed
safely but you must rename the algorithm if you change SHA256.
"""
algorithm = "pbkdf2_sha256"
iterations = 36000
digest = hashlib.sha256
def encode(self, password, salt, iterations=None):
assert password is not None
assert salt and '$' not in salt
if not iterations:
iterations = self.iterations
hash = pbkdf2(password, salt, iterations, digest=self.digest)
hash = base64.b64encode(hash).decode('ascii').strip()
return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash)
def verify(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
assert algorithm == self.algorithm
encoded_2 = self.encode(password, salt, int(iterations))
return constant_time_compare(encoded, encoded_2)
def safe_summary(self, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
assert algorithm == self.algorithm
return OrderedDict([
(_('algorithm'), algorithm),
(_('iterations'), iterations),
(_('salt'), mask_hash(salt)),
(_('hash'), mask_hash(hash)),
])
def must_update(self, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
return int(iterations) != self.iterations
def harden_runtime(self, password, encoded):
algorithm, iterations, salt, hash = encoded.split('$', 3)
extra_iterations = self.iterations - int(iterations)
if extra_iterations > 0:
self.encode(password, salt, extra_iterations)
正如你看到那样,你必须继承自BasePasswordHasher,并且重写 verify() , encode() 以及 safe_summary() 方法。
Django 是使用 PBKDF 2算法与36,000次的迭代使得它不那么容易被暴力破解法轻易攻破。密码用下面的格式储存:
algorithm$number of iterations$salt$password hash”
例:pbkdf2_sha256$36000$Lx7auRCc8FUI$eG9lX66cKFTos9sEcihhiSCjI6uqbr9ZrO+Iq3H9xDU=
二、自定义密码加密方法
1、在settings.py中加入自定义的加密算法:
PASSWORD_HASHERS = [
'myproject.hashers.MyMD5PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
]
2、再来看MyMD5PasswordHasher,这个是我自定义的加密方式,就是基本的md5,而django的MD5PasswordHasher是加盐的:
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)),
])
之后可以在数据库中看到,密码确实使用了自定义的加密方式。
3、修改认证方式
AUTHENTICATION_BACKENDS = (
'framework.mybackend.MyBackend', #新加
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
4、再来看自定义的认证方式
framework.mybackend.py:
import hashlib
from pro import models
from django.contrib.auth.backends import ModelBackend
class MyBackend(ModelBackend):
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自带的降低很多,但是需求就是这样的,必须满足。
来源:https://blog.csdn.net/bocai_xiaodaidai/article/details/103872716


猜你喜欢
- 前面简单介绍了Python列表基本操作,这里再来简单讲述一下Python元组相关操作>>> dir(tuple) #查看元
- 在分析查询性能时,考虑EXPLAIN关键字同样很管用。EXPLAIN关键字一般放在SELECT查询语句的前面,用于描述MySQL如何执行查询
- 首页url与视图函数的映射是通过@app.route()装饰器实现的。只有一个斜杠代表的是根目录——
- 什么是xml?xml即可扩展标记语言,它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。abc.xml<
- 作为一款「写作软件」在诞生之初就支持了 Markdown,Markdown 是一种「电子邮件」风格的「标记语言」,我们强烈推荐所有写作者学习
- 终于完成了偶的拖动窗口,花了近15个小时,庆祝一下(*^__^*);以前写了IE下的功能,于是又写了firefox下的功能,在firefox
- 应用OpenCV和Python进行SIFT算法的实现如下图为进行测试的gakki101和gakki102,分别验证基于BFmatcher、F
- 在网站开发的时候经常要用chr(),但本人比较懒没时间记那么多。于是到用到的时候就查,这样麻烦。现在将它写出来方便以后用到查,也方便大家!c
- 概述从今天开始, 小白我将带领大家一起来补充一下 数据库的知识.数据控制语言数据控制语言 (Data Control Language) 是
- 在ACCESS中更改控件的默认属性 Lisa Friedrichsen, 欧弗兰帕克,堪萨斯州 如果您在设计一个Microsoft ACCE
- 一、Go语言通道基础概念1.channel产生背景 线程之间进行通信的时候,会因为资源的争夺而产生竟态问
- 前言写过 CLI 常驻进程的老司机肯定遇到过这么一个问题:在需要更新程序的时候,我要怎样才能安全关闭老进程?你可能会想到 NGIN
- 如果用到数据筛选功能,可以使用x if condition else y的逻辑实现。如果使用的是纯Python,可以使用不断迭代的方式对每一
- 1. 引言深拷贝和浅拷贝是Python中重要的概念,本文重点介绍在NumPy中深拷贝和浅拷贝相关操作的定义和背后的原理。闲话少说,我们直接开
- 首先,有个单例对象,它上面挂了很多静态工具方法。其中有一个是each,用来遍历数组或对象。var nativeForEach = [].fo
- 如何使整个页面内容居中,如何使高度适应内容自动伸缩。这是学习CSS布局最常见的问题。下面就给出一个实际的例子,并详细解释。(本文的经验和是蓝
- Oracle不像SQLServer那样在存储过程中用Select就可以返回结果集,而是通过Out型的参数进行结果集返回的。实际上是利用REF
- 字符串就是一个话题中心。给字符串编号在很多很多情况下,我们都要对字符串中的每个字符进行操作(具体看后面的内容),要准确进行操作,必须做的一个
- k8s容器互联-flannel vxlan 原理篇容器系列文章容器系列视频vxlan 模式通信原理flannel 在为不同主机的pod分配i
- 背景有时本地服务器的时间不准了,需要同步互联网上的时间。解决方案NTP时间同步,找到一些可用的NTP服务器进行同步即可。通过获取一些大型网站