【Django】调用django的pbkdf2_sha256加密算法测试

基于django搭建的系统中,用到pbkdf2_sha256((Password-Based Key Derivation Function 2))加密算法,这里做些代码测试、总结。

  • PBKDF2简介
    • PBKDF2是一种基于密码的密钥派生函数,用于从用户提供的密码中生成加密密钥。
    • 全称是Password-Based Key Derivation Function 2,即基于密码的密钥派生函数2。
    • PBKDF2的主要目的是通过引入计算成本高的过程,使得从加密密钥中逆向推导出原始密码的难度大大增加,从而提高密码的安全性。

1.settings.py文件配置

python 复制代码
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

python 复制代码
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测试

python 复制代码
from django.contrib.auth.hashers import make_password, check_password

import 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.异常问题记录
python 复制代码
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参数引入示例如下:
相关推荐
李广坤14 小时前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
爱可生开源社区2 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1772 天前
《从零搭建NestJS项目》
数据库·typescript
加号32 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏2 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐2 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
QQ4022054962 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再2 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
starlaky2 天前
Django入门笔记
笔记·django