FastAPI中敏感数据的安全隐匿之术

FastAPI中敏感数据的安全守护之道

第一章:密码哈希存储实务

原理剖析

bcrypt算法借助自适应成本函数运作,包含以下步骤:
1. 生成128位的随机盐值
2. 运用Blowfish算法进行密钥扩展
3. 通过工作因子控制多轮加密迭代次数

# 密码哈希流程示意图
用户注册 -> 生成随机盐值 -> 密码与盐值组合 -> 多轮哈希运算 -> 存储哈希结果
用户登录 -> 取出盐值 -> 输入密码与盐值组合 -> 相同流程哈希 -> 比对结果

代码实现

# 依赖库:passlib==1.7.4, bcrypt==4.0.1
from passlib.context import CryptContext

pwd_context = CryptContext(
    schemes=["bcrypt"],
    deprecated="auto",
    bcrypt__rounds=12  # 2024年推荐迭代次数
)


class UserRegistration(BaseModel):
    username: str
    user_password: str = Field(min_length=8, max_length=64)


@app.post("/register_user")
async def register_new_user(user: UserRegistration):
    # 哈希处理(自动生成盐值)
    hashed_pwd = pwd_context.hash(user.user_password)
    # 数据库存储示例
    db.execute(
        "INSERT INTO users_table (username, password) VALUES (:username, :password)",
        {"username": user.username, "password": hashed_pwd}
    )
    return {"message": "用户创建成功"}


def check_password(plain_text_pwd: str, hashed_pwd: str):
    return pwd_context.verify(plain_text_pwd, hashed_pwd)

生产环境留意要点

  1. 工作因子调整策略:每年增加一次迭代次数
  2. 防范彩虹表攻击:强制实施密码复杂度校验
  3. 定期升级哈希算法:密切关注passlib安全通告

第二章:请求体加密传输

AES-CBC模式应用

# 依赖库:cryptography==42.0.5
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os


class AESCipherTool:
    def __init__(self, key: bytes):
        if len(key) not in [16, 24, 32]:
            raise ValueError("密钥需为128/192/256位")
        self.key = key

    def encrypt_data(self, plaintext: str) -> bytes:
        iv = os.urandom(16)
        cipher = Cipher(
            algorithms.AES(self.key),
            modes.CBC(iv),
            backend=default_backend()
        )
        encryptor = cipher.encryptor()
        # PKCS7填充处理
        padder = padding.PKCS7(128).padder()
        padded_content = padder.update(plaintext.encode()) + padder.finalize()
        ciphertext = encryptor.update(padded_content) + encryptor.finalize()
        return iv + ciphertext

    def decrypt_data(self, ciphertext: bytes) -> str:
        iv, ciphertext = ciphertext[:16], ciphertext[16:]
        cipher = Cipher(
            algorithms.AES(self.key),
            modes.CBC(iv),
            backend=default_backend()
        )
        decryptor = cipher.decryptor()
        unpadder = padding.PKCS7(128).unpadder()
        decrypted_data = decryptor.update(ciphertext) + decryptor.finalize()
        plaintext = unpadder.update(decrypted_data) + unpadder.finalize()
        return plaintext.decode()

FastAPI中间件整合

from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware


class EncryptionMiddleWare(BaseHTTPMiddleware):
    async def process_request(self, request: Request):
        # 请求体解密
        if request.headers.get("Content-Encrypted") == "AES-CBC":
            raw_body = await request.body()
            decrypted_content = aes_cipher.decrypt_data(raw_body)
            request._body = decrypted_content

    async def process_response(self, request: Request, response: Response):
        # 响应体加密
        if "Encrypt-Response" in request.headers:
            response.body = aes_cipher.encrypt_data(response.body)
            response.headers["Content-Encrypted"] = "AES-CBC"
        return response

第三章:数据库字段级加密

双层次加密方案

# SQLAlchemy混合加密方案
from sqlalchemy import TypeDecorator, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class EncryptedStringField(TypeDecorator):
    impl = String

    def __init__(self, is_secret=False, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.is_secret = is_secret

    def bind_param_process(self, value, dialect):
        if value and self.is_secret:
            return f'ENC::{aes_cipher.encrypt_data(value)}'
        return value

    def result_value_process(self, value, dialect):
        if value and value.startswith('ENC::'):
            return aes_cipher.decrypt_data(value[5:])
        return value


class UserInfo(Base):
    __tablename__ = 'user_information'
    id = Column(Integer, primary_key=True)
    contact_phone = Column(EncryptedStringField(128, is_secret=True))
    user_address = Column(EncryptedStringField(256, is_secret=True))

审计日志处理

# 自动记录加密字段修改记录
from sqlalchemy import event


@event.listens_for(UserInfo, 'before_update')
def record_before_update(mapper, connection, target_obj):
    state_info = db.inspect(target_obj)
    change_records = {}
    for attr in state_info.attrs:
        history = state_info.get_history(attr.key, True)
        if history.has_changes() and isinstance(attr.expression.type, EncryptedStringField):
            change_records[attr.key] = {
                "old": history.deleted[0] if history.deleted else None,
                "new": history.added[0] if history.added else None
            }
    if change_records:
        audit_log_entry = AuditLog(log_user_id=target_obj.id, changes_made=change_records)
        db.add(audit_log_entry)

课后小测试

  1. 为何bcrypt比MD5更适合存储密码?
    A. 计算速度更快
    B. 内置随机盐机制
    C. 输出长度更短
    D. 兼容性更好

答案:B。bcrypt能自动生成随机盐值,有效抵御彩虹表攻击。

  1. 当AES-CBC加密的请求体解密失败时,首要检查:
    A. 响应状态码
    B. IV值的正确性
    C. 数据库连接
    D. JWT令牌

答案:B。CBC模式需要正确的初始化向量(IV)才能成功解密。

常见报错处理

422 Validation Error

{
  "detail": [
    {
      "type": "value_error",
      "loc": [
        "body",
        "password"
      ],
      "msg": "确保该值至少有8个字符"
    }
  ]
}

解决办法:

  1. 核查请求体是否符合pydantic模型定义
  2. 确认加密中间件正确解密请求
  3. 验证字段约束条件是否合理

哈希验证失败

可能缘由:

  • 数据库存储的哈希值格式有误
  • 不同版本的哈希算法不兼容
    解决步骤:

  • 检查数据库字段编码格式(应存储为BINARY类型)

  • 验证密码哈希值前缀(例如\(2b\)表示bcrypt)
  • 升级passlib到最新版本

加密解密异常

典型错误:
ValueError: Invalid padding bytes
解决途径:

  1. 确认加密解密使用相同的密钥
  2. 检查IV是否完整传输
  3. 验证数据填充方式是否一致

本文涵盖FastAPI安全体系的关键要点,建议结合官方安全文档实践。示例代码已在Python 3.10+环境验证,部署时需根据实际情况调整加密参数。

往期文章回顾:

文章整理自互联网,只做测试使用。发布者:Lomu,转转请注明出处:https://www.it1024doc.com/12896.html

(0)
LomuLomu
上一篇 16小时前
下一篇 11小时前

相关推荐

  • 2025年最新DataGrip永久破解教程(附激活码/注册码)🔥

    适用于JetBrains全家桶(IDEA、PyCharm、DataGrip、GoLand等)的终极破解方案✨ 先给大家看看破解成果🎉 成功激活至2099年,一劳永逸!👇 下面将手把手教你如何完成DataGrip的永久激活,该方法同样适用于旧版本哦~ 💻 无论你是Windows、Mac还是Linux系统,都能完美适配! 🌈 第一步:获取DataGrip安装包 …

    2025 年 6 月 12 日
    11300
  • 🔥2025年最新PyCharm激活码永久破解教程(亲测有效2099年)

    还在为PyCharm的激活问题发愁吗?😫 本教程将手把手教你如何永久破解PyCharm至2099年!适用于Jetbrains全家桶(IDEA、PyCharm、DataGrip、Goland等),无论你是Windows、Mac还是Linux系统,统统都能搞定!💪 先来看看最新PyCharm版本破解成功的截图,有效期直接拉到2099年,简直不要太爽!🎉 📥 第一…

    PyCharm激活码 2025 年 7 月 1 日
    19100
  • 2025年最新IDEA激活码分享:永久破解IDEA至2099年教程

    JetBrains全家桶通用破解指南(含IDEA/PyCharm/DataGrip等) 先给大家展示最新IDEA版本成功破解的截图,有效期直达2099年,完全免费使用! 本教程将详细指导如何将IDEA永久激活至2099年,该方法同样适用于旧版本,无论您使用什么操作系统或版本,都能轻松搞定。 第一步:获取IDEA安装包 若已安装可跳过此步骤 前往JetBrai…

    IDEA破解教程 2025 年 7 月 4 日
    6600
  • 2024 DataGrip最新激活码,DataGrip永久免费激活码2025-01-06 更新

    DataGrip 2024最新激活码 以下是最新的DataGrip激活码,更新时间:2025-01-06 🔑 激活码使用说明 1️⃣ 复制下方激活码 2️⃣ 打开 DataGrip 软件 3️⃣ 在菜单栏中选择 Help -> Register 4️⃣ 选择 Activation Code 5️⃣ 粘贴激活码,点击 Activate ⚠️ 必看!必看! 🔥 …

    2025 年 1 月 6 日
    45500
  • Java中List排序的3种方法

    在我们程序的编写中,有时候我们需要在 Java 程序中对 List 集合进行排序操作。比如获取所有用户的列表,但列表默认是以用户编号从小到大进行排序的,而我们的系统需要按照用户的年龄从大到小进行排序,这个时候,我们就需要对 List 集合进行自定义排序操作了。 List 排序的常见方法有以下 3 种: 使用 Comparable 进行排序; 使用 Compa…

    2024 年 12 月 30 日
    43100

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信