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',  # 类前面是你的中间件文件名和存放文件的路径
]
相关推荐
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
QQ4022054963 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再3 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
starlaky3 天前
Django入门笔记
笔记·django
QQ5110082853 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe3 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
B站计算机毕业设计超人3 天前
计算机毕业设计Django+Vue.js高考推荐系统 高考可视化 大数据毕业设计(源码+LW文档+PPT+详细讲解)
大数据·vue.js·hadoop·django·毕业设计·课程设计·推荐算法
计算机程序猿学长3 天前
大数据毕业设计-基于django的音乐网站数据分析管理系统的设计与实现(源码+LW+部署文档+全bao+远程调试+代码讲解等)
大数据·django·课程设计
B站计算机毕业设计超人3 天前
计算机毕业设计Django+Vue.js音乐推荐系统 音乐可视化 大数据毕业设计 (源码+文档+PPT+讲解)
大数据·vue.js·hadoop·python·spark·django·课程设计
B站_计算机毕业设计之家3 天前
电影知识图谱推荐问答系统 | Python Django系统 Neo4j MySQL Echarts 协同过滤 大数据 人工智能 毕业设计源码(建议收藏)✅
人工智能·python·机器学习·django·毕业设计·echarts·知识图谱