You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SQLAlchemy ORM在MySQL中存储哈希密码的Schema及字节改造咨询

使用SQLAlchemy ORM在MySQL中存储哈希密码的Schema方案

修改后的User模型(支持字节类型存储哈希密码)

from sqlalchemy import LargeBinary, String, DateTime
from sqlalchemy.orm import Mapped, mapped_column
import datetime
import bcrypt

class User(db.Model):
    username: Mapped[str] = mapped_column(String(40), primary_key=True, nullable=False)
    first_name: Mapped[str] = mapped_column(String(40))
    last_name: Mapped[str] = mapped_column(String(40))
    # 用LargeBinary存储字节类型的哈希密码,指定长度匹配哈希算法输出(bcrypt固定60字节)
    password: Mapped[bytes] = mapped_column(LargeBinary(60), nullable=False)
    account_created: Mapped[datetime.datetime] = mapped_column(default=datetime.datetime.utcnow)
    account_updated: Mapped[datetime.datetime] = mapped_column(
        default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
    
    # 封装密码哈希逻辑
    def set_password(self, plain_password: str):
        # 生成盐并哈希密码,直接得到字节类型结果
        hashed_pw = bcrypt.hashpw(plain_password.encode('utf-8'), bcrypt.gensalt())
        self.password = hashed_pw
    
    # 封装密码验证逻辑
    def check_password(self, plain_password: str) -> bool:
        return bcrypt.checkpw(plain_password.encode('utf-8'), self.password)

关键修改说明

  • 字段类型调整:将password的类型从Mapped[str]改为Mapped[bytes],数据库端使用LargeBinary类型,MySQL会自动映射为适配字节存储的类型(指定长度时为VARBINARY,未指定则为LONGBLOB)。
  • 指定存储长度:根据你使用的哈希算法固定长度设置LargeBinary的参数,比如bcrypt生成的哈希结果固定为60字节,指定长度能让数据库存储更高效。
  • 安全逻辑封装:添加set_password和check_password方法,避免直接处理明文密码,使用成熟的哈希库(如bcrypt)自动处理盐生成、哈希迭代等安全细节,杜绝手动实现哈希的安全风险。

注意事项

  • 不要使用MD5、SHA-1等弱哈希算法,优先选择bcrypt、Argon2这类专门为密码设计的自适应哈希算法。
  • 确保password字段设置为nullable=False,强制用户必须设置密码。
  • 哈希后的字节数据无需额外编码,直接存入LargeBinary字段即可,读取时直接得到原始哈希字节用于验证。

内容的提问来源于stack exchange,提问作者venkat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 19:37:02