Django AES加密:如何在保存用户上传的文件之前对其进行加密?

时间:2019-07-17 11:19:34

标签: django python-3.x encryption

我想在保存之前用django加密用户上传的文件。

当用户通过POST请求发送文件时,我得到一个“ InMemoryUploadedFile”类型的对象。

在保存文件之前如何加密文件?我目前使用pyAesCrypt加密文件,但无法将“ InMemoryUploadedFile”对象传递给它。我设法将它们保存为:

import pyAesCrypt

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

1 个答案:

答案 0 :(得分:1)

我最近问了这个问题,一个用户告诉我使用一个具有更好社区支持的软件包。它是 pyca /密码学。我陷入同样的​​困境,找到了解决方案。请注意,我使用Django Rest Framework。

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

我将以一个excel文件为例,但是您实际上可以使用任何文件。

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.

在为用户提供服务之前解密文件。读取文件并将其写入BytesIO,然后即可将文件提供给用户。

相关问题