django对称加密算法中间件

在Django中,中间件可以用来处理请求和响应的全局生命周期。如果你想要创建一个中间件来加密响应数据以便前端接收,你需要实现process_response方法。下面是一个简单的示例,该中间件使用一个基本的对称加密算法:

python 复制代码
from django.utils.deprecation import MiddlewareMixin
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import base64
from django.utils.encoding import force_bytes, force_text


class EncryptionMiddleware(MiddlewareMixin):

    def process_response(self, request, response):
        # 将response.content字节码转为字符串,再将字符串中的中文转为unicode码,为了解决进行加密时会提示加密的字符串太长的报错
        response_content = response.content.decode('utf-8').encode('unicode_escape')
        if 200 <= response.status_code <= 400 and isinstance(response_content, bytes):  # 只处理成功状态且有内容的响应
            # 获取原始响应数据
            original_content = force_text(response_content)

            with open("rsa.private.pem", mode="r") as f:
                pubkey = f.read()
            # 加密响应数据
            encrypted_content = self.rsa_long_encrypt(original_content, pubkey)

            # 替换响应内容为加密后的数据,并设置合适的Content-Type以指示前端数据已加密
            response.content = encrypted_content.encode('utf-8')
            response['Content-Type'] = 'application/encrypted-data'  # 自定义类型,前端需理解如何处理

        return response

    def rsa_long_encrypt(self, msg, pub_key_str, length=100):
        """
        单次加密串的长度最大为 (key_size/8)-11
        1024bit的证书用100, 2048bit的证书用 200
        """
        pubobj = RSA.importKey(pub_key_str)
        pubobj = Cipher_pkcs1_v1_5.new(pubobj)
        res = []
        for i in range(0, len(msg), length):
            print(msg[i:i + length])
            res.append(
                str(
                    base64.b64encode(pubobj.encrypt(
                        msg[i:i + length].encode(encoding="utf-8"))), 'utf-8'
                )
            )
        return "".join(res)

最后在setting.py文件中把写好的类注册到中间件中就可以了

python 复制代码
MIDDLEWARE = [
    ....
    'yourpath.middleware.EncryptionMiddleware',  # 类前面是你的中间件文件名和存放文件的路径
]
相关推荐
前端不太难8 小时前
从失败到 87.5%:OpenClaw 的任务进化
状态模式·openclaw
Muyuan199812 小时前
28.Paper RAG Agent 开发记录:修复 LLM Rerank 的解析、Fallback 与可验证性
linux·人工智能·windows·python·django·fastapi
前端不太难18 小时前
鸿蒙PC和App:都在走向 System
华为·状态模式·harmonyos
运维全栈笔记1 天前
Linux安装配置Tomcat保姆级教程:从部署到性能调优
linux·服务器·中间件·tomcat·apache·web
必胜刻1 天前
全面解析 Token:从入门到 JWT 实战
golang·状态模式·web·前后端交互
Muyuan19981 天前
27.RAG 系统中的上下文充分性判断:从 Chunk 数量、FAISS 距离到 LLM Relevance Gate
python·django·pdf·fastapi·faiss
程序媛徐师姐2 天前
Python基于Django的小区果蔬预定系统【附源码、文档说明】
python·django·小区果蔬预定系统·果蔬预定·python小区果蔬预定系统·小区果蔬预定·python果蔬预定系统
木斯佳2 天前
前端八股文面经大全:腾讯前端实习二、三OC面(2026-04-27)·面经深度解析
前端·状态模式
许长安2 天前
protobuf 使用详解
c++·经验分享·笔记·中间件
码界筑梦坊3 天前
111-基于Python的中国旅游用户数据可视化分析系统
python·信息可视化·django·毕业设计·旅游