- core/: database/redis_client/jwt/password/response/exceptions/security/logger/deps/middleware/app - create_app 迁移到 core/app.py,中间件注册顺序与异常处理器原样保留 - extensions/ utils/ apps/ 旧文件全部改为 re-export 垫片,import 路径保持兼容 - 新增 core 单元测试(jwt/password/response/request 共 12 个) Co-Authored-By: Claude <noreply@anthropic.com>
35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
# +======================================================================
|
|
# | DjangoAdmin 企业数字化开发平台 [ 赋能开发者,助力企业发展 ]
|
|
# +----------------------------------------------------------------------
|
|
# | Copyright (c) 2021-2026 一米阳光团队 版权所有
|
|
# | 开源协议: Apache-2.0
|
|
# +======================================================================
|
|
# 由 utils/password.py 迁移而来。
|
|
|
|
"""密码加密工具:基于 bcrypt 的双重加盐方案。"""
|
|
|
|
import secrets
|
|
|
|
import bcrypt
|
|
|
|
# bcrypt 工作因子,值越大计算越慢越安全,默认12(约250ms)
|
|
BCRYPT_ROUNDS = 12
|
|
|
|
|
|
def generate_salt(length: int = 10) -> str:
|
|
"""生成随机盐值"""
|
|
return secrets.token_urlsafe(length)[:length]
|
|
|
|
|
|
def encrypt_password(password: str, salt: str) -> str:
|
|
"""使用 bcrypt 加密密码(外部 salt 双重加盐)"""
|
|
combined = (password + salt).encode('utf-8')
|
|
hashed = bcrypt.hashpw(combined, bcrypt.gensalt(rounds=BCRYPT_ROUNDS))
|
|
return hashed.decode('utf-8')
|
|
|
|
|
|
def verify_password(password: str, salt: str, hashed: str) -> bool:
|
|
"""验证密码是否正确"""
|
|
combined = (password + salt).encode('utf-8')
|
|
return bcrypt.checkpw(combined, hashed.encode('utf-8'))
|