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',  # 类前面是你的中间件文件名和存放文件的路径
]
相关推荐
B站_计算机毕业设计之家5 小时前
深度血虚:Django水果检测识别系统 CNN卷积神经网络算法 python语言 计算机 大数据✅
python·深度学习·计算机视觉·信息可视化·分类·cnn·django
Q_Q5110082855 小时前
python+django/flask的校园活动中心场地预约系统
spring boot·python·django·flask·node.js·php
Q_Q19632884758 小时前
python+django/flask基于机器学习的就业岗位推荐系统
spring boot·python·django·flask·node.js·php
aini_lovee10 小时前
Node.js 中的中间件机制与 Express 应用
中间件·node.js·express
dreams_dream10 小时前
Django序列化器
后端·python·django
懷淰メ10 小时前
python3GUI--短视频社交软件 By:Django+PyQt5(前后端分离项目)
后端·python·django·音视频·pyqt·抖音·前后端
zhangbaolin10 小时前
langchain agent的中间件
中间件·langchain·大模型·agent
little_xianzhong11 小时前
三个常听到的消息/中间件MQTT RabbitMQ Kafka
java·笔记·中间件·消息队列
码界筑梦坊12 小时前
243-基于Django与VUE的笔记本电脑数据可视化分析系统
vue.js·python·信息可视化·数据分析·django·毕业设计·echarts
Q_Q5110082851 天前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php