refactor: P2 core+common 建设(应用工厂/扩展/工具层迁入 src/)
【结构】 - src/core/:database/response/jwt/password/security/redis_client/mail/scheduler - src/common/:base_model/base_db/forms(base_form+fields)/constants/utils - src/models_registry.py:模型聚合器(Flask-Migrate 全量表识别) 【绞杀者 shim】extensions/、utils/、application/constants|forms|models 打兼容转发 【兼容修复】应用工厂抽取至 application/factory.py(P2 前置,P1 已完成) 【基线修复】application/models(25) + middleware(7) 原被嵌套 .gitignore(*) 误排除出版本库,已补入(base_model/base_db 现为 shim,原版在 src/common/) 【登记既有缺陷】 1. flask db CLI 因 .env FLASK_VERSION 与 --version 冲突报错 → Makefile 已加 FLASK_SKIP_DOTENV=1 2. 本机 Redis 未设密码但 REDIS_AUTH=True,/captcha 报 AUTH 错误(环境问题) 【验收】22 模型表全量识别;src/ flake8 零告警;pytest 5 passed;应用启动; /login 表单校验、/user/page 鉴权拦截冒烟正常 Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude
parent
92130ef070
commit
658ee6d596
+4
-68
@@ -1,72 +1,8 @@
|
||||
"""
|
||||
密码加密工具模块
|
||||
兼容 shim(绞杀者迁移期间保留)
|
||||
=============================================================
|
||||
|
||||
该模块提供基于 bcrypt 的密码加密和验证功能。
|
||||
采用 bcrypt(password + salt) 方案,bcrypt 内置盐与外部 salt 双重加盐,
|
||||
确保相同密码产生不同哈希,有效抵御彩虹表攻击。
|
||||
|
||||
主要功能:
|
||||
1. 生成随机盐值(generate_salt)
|
||||
2. 密码加密(encrypt_password)- bcrypt(password + salt)
|
||||
3. 密码验证(verify_password)
|
||||
|
||||
所属包: utils
|
||||
所在文件: utils/password.py
|
||||
依赖模块: bcrypt - 密码哈希第三方库
|
||||
secrets - 安全随机数生成模块
|
||||
密码工具已迁移至 src/core/password.py。
|
||||
本文件仅作兼容转发,最终在 P7(切尾)阶段删除。
|
||||
"""
|
||||
|
||||
import secrets
|
||||
|
||||
import bcrypt
|
||||
|
||||
# bcrypt 工作因子,值越大计算越慢越安全,默认12(约250ms)
|
||||
BCRYPT_ROUNDS = 12
|
||||
|
||||
|
||||
def generate_salt(length: int = 10) -> str:
|
||||
"""
|
||||
生成随机盐值
|
||||
|
||||
Args:
|
||||
length: 盐值长度,默认10位
|
||||
|
||||
Returns:
|
||||
str: 随机盐值字符串
|
||||
"""
|
||||
return secrets.token_urlsafe(length)[:length]
|
||||
|
||||
|
||||
def encrypt_password(password: str, salt: str) -> str:
|
||||
"""
|
||||
使用 bcrypt 加密密码
|
||||
|
||||
将密码与外部 salt 拼接后进行 bcrypt 哈希,实现双重加盐。
|
||||
|
||||
Args:
|
||||
password: 明文密码
|
||||
salt: 外部盐值
|
||||
|
||||
Returns:
|
||||
str: bcrypt 哈希字符串(60字符)
|
||||
"""
|
||||
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:
|
||||
"""
|
||||
验证密码是否正确
|
||||
|
||||
Args:
|
||||
password: 待验证的明文密码
|
||||
salt: 外部盐值
|
||||
hashed: 存储的 bcrypt 哈希值
|
||||
|
||||
Returns:
|
||||
bool: 密码是否匹配
|
||||
"""
|
||||
combined = (password + salt).encode('utf-8')
|
||||
return bcrypt.checkpw(combined, hashed.encode('utf-8'))
|
||||
from src.core.password import * # noqa: F401,F403
|
||||
|
||||
Reference in New Issue
Block a user