如何加密 DRF 中的响应?

mah*_*yni 2 python encryption django python-3.x django-rest-framework

我想加密我的 DRF 项目 API 响应 有没有办法加密大型响应,以便我只能访问前端侧的数据?我想加密所有回复。

Eli*_*ado 5

是的,这是可能的,而且我自己也应用过。您可以使用直接应用于序列化器的 AES256(高级加密标准 256)来完成此操作。

基本上加密将依赖 django 的密钥来加密和解密。

因此,将有两个函数encrypt()decrypt()您将在其中应用需要将其加密发送到数据库中的每个字段。以及在端点命中 GET 请求时解密。

您可以在此处获取这些函数示例和实现。

例子:

from rest_framework import serializers
from django.conf import settings
from aesencryption import AESCipher

aes = AESCipher(settings.SECRET_KEY[:16], 32)


class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = ['name', 'address']

    def create(self, validated_data):
        # Here the data will be inserted into the db encrypted.
        validated_data['name'] = aes.encrypt(validated_data['name'])
        validated_data['address'] = aes.encrypt(validated_data['address'])
        return MyModel.objects.create(**validated_data)

    def to_representation(self, instance):
        # Here you will decrypt the data from the db.
        return {
            'name': aes.decrypt(instance.name),
            'address': aes.decrypt(instance.address)
        }

Run Code Online (Sandbox Code Playgroud)

警告:更改 Secrete_key 时要小心。如果丢失,则无法恢复数据。