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',  # 类前面是你的中间件文件名和存放文件的路径
]
相关推荐
今年下半年5 小时前
【Spring Boot】多种存储文件(FastDFS / MinIO / 阿里云 OSS)接入设计说明(附源码)
spring boot·分布式·中间件·简单工厂模式·策略模式
言乐68 小时前
Python自动去除水印
开发语言·python·django·virtualenv·pygame
小蒜学长9 小时前
基于Python的动物救助站管理系统的设计与实现(代码+数据库+LW)
数据库·后端·python·django·动物救助
言乐69 小时前
Python实现关税自动计算模型
开发语言·python·django·virtualenv·pygame
青山木13 小时前
秒杀系统设计(二):数据正确性——防超卖、分布式锁与一人一单
分布式·后端·mysql·中间件·架构
Maiko Star16 小时前
* LangChain 自定义中间件详解:Hook、装饰器、类与执行顺序
中间件·langchain
FYKJ_20101 天前
springboot贺州地方新闻网站87812-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·django·课程设计
幽络源小助理1 天前
WordPress REST API 深度实战:从自定义端点到 Headless CMS 架构全拆解
架构·状态模式
katasea1 天前
第05章:信创技术栈选型:服务器、操作系统、数据库、中间件适配对比
服务器·数据库·中间件
高洁012 天前
AI视频生成技术:从静态图文到动态视觉的内容智能革命
python·深度学习·django·transformer·tornado