I want to encrypt my DRF project APIs responses Is there a way to encrypt large responses so that I only have access to the data on the front end side? I want to encrypt all responses.
Asked
Active
Viewed 2,265 times
2
-
actually if you are using https communication everything should be fine but if you want you can create your own encryption function as utils.py that encrypt the data while saving it in the db and decrypt it while serving it on the front-end , or you can use this https://docs.djangoproject.com/en/4.0/topics/signing/ – Thierno Amadou Sow Apr 24 '22 at 17:50
-
Https does the same. You should look at allow only frontend url to access django and block all others, like other urls trying to use your api endpoint and Postman. – Ranu Vijay Apr 24 '22 at 18:32
1 Answers
5
Yes it is possible and I had applied it myself. You can do it using AES256 (Advanced encryption standard 256) applied directly into the serializer.
Basically the encryption will be relying on the django's secrete key to encrypt and decrypt.
Therefore, there will be two functions encrypt()
and decrypt()
where you will apply for each field that you need to send them encrypted into the database. As well as to decrypt when the endpoint hit the GET request.
You can get these function example and implementation here.
Example:
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)
}
Warning: Be careful when changing the secrete_key. If you lose it there is no way you can get the data back.

Elias Prado
- 1,518
- 2
- 17
- 32
-
In terms of Django could explain me how could it be exposed in a way I can perform it here? Now in terms of encryption, aes256 is used by banks and governments as well as powerful military data encryption. As far as I know is the best encryption standard. – Elias Prado Apr 25 '22 at 06:43
-
How is it different from using SSL certificate to secure the connection ? – Florent Sep 02 '22 at 08:22
-
1Because it is an advance encryption. Where it can be worked in conjunction with ssl wich is transational only. Imagine sending top secret content with ssl only? In this case the encryption is set into the database where the key will be encrypted with the web hosting with ssl I guess. – Elias Prado Sep 02 '22 at 19:48