簡體   English   中英

Django AES 加密:如何在保存用戶上傳的文件之前對其進行加密?

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

我想在保存之前在 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)

我最近問了這個問題,一位用戶告訴我使用具有更好社區支持的軟件包。 它是pyca/cryptography 我被困在同樣的事情上,我找到了解決方案。 請注意,我使用 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,然后您可以將該文件提供給用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM