简体   繁体   中英

Django AES Encryption : how encrypt user-uploaded files before they are saved?

I want to encrypt user uploaded files in django before saving them.

When user send files through POST requests, I get a "InMemoryUploadedFile" type object.

How can I encrypt the files before saving them ? I currently use pyAesCrypt to encrypt files but I can't manage to pass in it the "InMemoryUploadedFile" objects. I manage to only encrypt them after they are saved with :

import pyAesCrypt

with open("*FileName*", "rb") as InputFile:
    with open("*OutputFileName*", "wb+") as OutputFile:
        pyAesCrypt.encryptStream(InputFile, OutputFile, Password, BufferSize)

I recently asked this questions and a user told me to use a package with better community support. It is pyca/cryptography . I was stuck in the same thing and I found a solution. Mind that, I use Django Rest Framework.

from cryptography.fernet import Fernet
# Generate a key and store safely
key = Fernet.generate_key()
f = Fernet(key)

I'll take an excel file for example but you could actually use any file.

import pandas as pd
import io
from django.core.files.uploadedfile import SimpleUploadedFile

# Request file from user and load the file into a dataframe
df = pd.read_excel(request.FILES('file_name'))
# Create BytesIO
output = io.BytesIO()
# Output df to BytesIO
df.to_excel(output, index=False)
# Encrypt data (BytesIO)
encrypted_out = f.encrypt(output.getvalue())
# Export encrypted file
output_file = SimpleUploadedFile('<some_file_name.extension>',encrypted_out)
# Typically you would pass this through a serializer.

To decrypt the file before you can serve the user. Read the file and write it to BytesIO and then you can serve the file to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM