chore: 基线提交(重构前代码快照)
- git 初始化 + .gitignore 补全(根 .env / logs / instance / __pycache__ 等) - 修复 utils/.gitignore 误将整个 utils/ 源码层忽略的问题,补入全部工具源码(含 ip2region.xdb) - 含后端全部代码:application / extensions / utils / config / migrations - 含前端 ui/(后续整体迁走) - 不含根 .env(含密钥,本地保留) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
密码加密工具模块
|
||||
=============================================================
|
||||
|
||||
该模块提供基于 bcrypt 的密码加密和验证功能。
|
||||
采用 bcrypt(password + salt) 方案,bcrypt 内置盐与外部 salt 双重加盐,
|
||||
确保相同密码产生不同哈希,有效抵御彩虹表攻击。
|
||||
|
||||
主要功能:
|
||||
1. 生成随机盐值(generate_salt)
|
||||
2. 密码加密(encrypt_password)- bcrypt(password + salt)
|
||||
3. 密码验证(verify_password)
|
||||
|
||||
所属包: utils
|
||||
所在文件: utils/password.py
|
||||
依赖模块: bcrypt - 密码哈希第三方库
|
||||
secrets - 安全随机数生成模块
|
||||
"""
|
||||
|
||||
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'))
|
||||
Reference in New Issue
Block a user