基于
django
搭建的系统中,用到pbkdf2_sha256((Password-Based Key Derivation Function 2))
加密算法,这里做些代码测试、总结。
- PBKDF2简介
- PBKDF2是一种基于密码的密钥派生函数,用于从用户提供的密码中生成加密密钥。
- 全称是
Password-Based Key Derivation Function 2
,即基于密码的密钥派生函数2。 - PBKDF2的主要目的是通过引入计算成本高的过程,使得从加密密钥中逆向推导出原始密码的难度大大增加,从而提高密码的安全性。
1.settings.py
文件配置
PASSWORD_HASHERS = ('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',
)SECRET_KEY = '9z%v-4&h$86qo@o8%c7ep^it*5$%sscl5hd$emb070pgo=1$6#'
2.生成SECRET KEY
from django.core.management.utils import get_random_secret_key
print( get_random_secret_key() )# hgic$t55335b7(z9h(gs&1j2+ralahabczs-hq0h&49erm1^&k
3.pbkdf2_sha256测试
from django.contrib.auth.hashers import make_password, check_passwordimport os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'YouliTest.settings')
# django.setup()# DJANGO_SETTINGS_MODULE=YouliTest.settings;pwd = '123456789'
mkpwd = make_password(pwd, None, 'pbkdf2_sha256') # 创建django密码,第三个参数为加密算法
print( 'make_password 测试: %s' % (mkpwd) )mkpwd_bool = check_password(pwd, mkpwd) # 返回的是一个bool类型的值,验证密码正确与否
print( 'check_password 测试: %r' % (mkpwd_bool) )# make_password 测试: pbkdf2_sha256$100000$CsSTgYxLUkkr$jHH29Qq+QZ2JoTXBPKymXjYBQoXPWNO9V9ZAk+I9V3Q=
# check_password 测试: True
4.异常问题记录
django.core.exceptions.ImproperlyConfigured: Requested setting PASSWORD_HASHERS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
- 问题原因
settings.py
文件未配置,配置好后需要在代码中引入或在运行参数中引入
Run/Debug Configurations
参数引入示例如下: