fastapi: passlib报错ValueError: password cannot be longer than 72 bytes, truncate manually if necessary (e.g. my_password[:72])
一,报错信息
报错代码
from passlib.context import CryptContext
# 密码哈希上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# --- 工具函数 ---
def verify_password(plain_password, hashed_password):
"""验证明文密码是否与哈希密码匹配"""
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
"""生成密码哈希"""
return pwd_context.hash(password)
报错信息
File "/data/python/fastapi/demo1/venv/lib/python3.10/site-packages/passlib/handlers/bcrypt.py", line 655, in _calc_checksum
hash = _bcrypt.hashpw(secret, config)
ValueError: password cannot be longer than 72 bytes, truncate manually if necessary (e.g. my_password[:72])
二,原因
I closed it because I found that passlib hasn't been updated since 8 Oct 2020 and doesn't seem to be maintained.
A fix is to use bcrypt directly:
三,解决:
把代码替换为:
按github上用户的建议,直接使用bcrypt这个库替代passlib
import bcrypt
def get_password_hash(password: str) -> str:
"""Hash a password using bcrypt"""
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def verify_password(plain_password: str, hashed: str) -> bool:
"""Verify a password against its hash"""
return bcrypt.checkpw(
plain_password.encode("utf-8"),
hashed.encode("utf-8"),
)
浙公网安备 33010602011771号