Skip to main content

Django Encrypted Files

Encrypt files uploaded to your Django application.

This package uses AES in CTR mode to encrypt files via an upload handler.

The upload handler encrypts data as it is recieved during upload, so only encrypted data is ever written to temporary files.

Files can then be decrypted with the included EncryptedFile class, which is a file-like object that decrypts data transparently.

Installation

Via pip:

pip install django-encrypted-files

Usage

Add the encrypted_files app to your INSTALLED_APPS setting:

settings.py

INSTALLED_APPS = [
    ...
    'encrypted_files',
    ...
]

Add an encryption key to use. This should be 16, 24, or 32 bytes long:

settings.py

AES_KEY = b'\x1a>\xf8\xcd\xe2\x8e_~V\x14\x98\xc2\x1f\xf9\xea\xf8\xd7c\xb3`!d\xd4\xe3+\xf7Q\x83\xb5~\x8f\xdd'

If you want to encrypt ALL uploaded files, add the EncryptedFileUploadHandler as the first handler:

settings.py

FILE_UPLOAD_HANDLERS = [
    "encrypted_files.uploadhandler.EncryptedFileUploadHandler",
    "django.core.files.uploadhandler.MemoryFileUploadHandler",
    "django.core.files.uploadhandler.TemporaryFileUploadHandler"
]

You can also use the encrypted file upload handler for a specific view:

views.py

from .models import ModelWithFile
from django.core.files.uploadhandler import MemoryFileUploadHandler, TemporaryFileUploadHandler
from django.views.generic.edit import CreateView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt, csrf_protect

@method_decorator(csrf_exempt, 'dispatch')
class CreateEncryptedFile(CreateView):
    model = ModelWithFile
    fields = ["file"]

    def post(self, request, *args, **kwargs):
        request.upload_handlers = [
            EncryptedFileUploadHandler(request=request),
            MemoryFileUploadHandler(request=request),
            TemporaryFileUploadHandler(request=request)
        ]  
        return self._post(request)

    @method_decorator(csrf_protect)
    def _post(self, request):
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

Use regular FileFields for file uploads. When you want to decrypt the file, use the EncryptedFile helper class

views.py

from .models import ModelWithFile
from encrypted_files.base import EncryptedFile
from django.http import HttpResponse

def decrypted(request,pk):
    f = ModelWithFile.objects.get(pk=pk).file
    ef = EncryptedFile(f)
    return HttpResponse(ef.read())

The EncryptedFileUploadHandler and EncryptedFile classes also take a key input if you want to use a custom key (based on the user, for example):

handler = EncryptedFileUploadHandler(request=request,key=custom_key_for_this_request)

You would then use the same key when decrypting:

ef = EncryptedFile(file,key=custom_key_for_this_request)

The EncryptedFile class is a wrapper around django's File class. It performs the decryption and counter/pointer management when .read() and .seek() are called. It can be used as a file-like object for other processing purposes, but is read-only.

How It Works

When a file is POSTed to your application, its raw byte data is passed through a series of upload handlers. The default behavior is to load the file into memory if it is small, or stream it to a temporary file if large. Then, it's moved to its "upload_to" location.

The EncryptedFileUploadHandler acts as a barrier between these default handlers, and the raw data. It prevents the unencrypted file data from being written to a temp file, by encrypting it before passing it along. It doesn't save any data, just encrypts it and passes it along.

raw bytes -> Encryption -> temp file -> final file

When the file starts the upload, the EncryptedFileUploadHandler adds 16 bytes to the start of the file. This is the nonce used to encrypt the data.

[16-byte nonce][...rest of the file (encrypted)...]
                ^ calling .seek(0) will move here

When the file needs to be decrypted, the EncryptedFile helper will read the first 16 bytes to get the nonce, then expose the rest of the file as if it starts at position 0. Methods like .seek() and .tell() are automatically corrected to make the file act like it's not encrypted at all.

In order to decrypt arbitrary amounts of data from arbitrary positions, the EncryptedFile class automatically loads enough 16-byte blocks to decrypt, then strips away the unneeded data. The cursor in the underlying encrypted file is always at the start of a block

        v .seek(4) will move here internally
[nonce][0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15][16 17 18 ...
              ^ but a subsequent .read(5) will start here
        |-----------------------------------| The underlying read will read this
              |-------| but return this data, decrypted

Another example:

        v .seek(12) moves here internally
[nonce][0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15][16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]
                                  ^ The "decrypted" pointer moves here
        call .read(6)             |                |
        |------------------------------------------------------------------------------------| This is read
                                  |----------------| This is returned
                                               ^ the internal pointer ends up here (pos 16)
                                                     ^ the "decrypted" pointer ends up here (pos 18)

Counters

When blocks are read, the counter is updated as well, based on where the internal pointer ends up. In the event of a counter overflow, it will wrap back to zero. This is the same behavior that the cryptography package uses internally.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_encrypted_files-0.0.7.tar.gz (7.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_encrypted_files-0.0.7-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file django_encrypted_files-0.0.7.tar.gz.

File metadata

  • Download URL: django_encrypted_files-0.0.7.tar.gz
  • Upload date:
  • Size: 7.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.7.6

File hashes

Hashes for django_encrypted_files-0.0.7.tar.gz
Algorithm Hash digest
SHA256 2e68ad74997c16d8071168872f1bc77bb8e1a573ebfc31bbad57ffcc2268e3b1
MD5 444d5af15f86d3749b8c61fc387d4323
BLAKE2b-256 d10dd302f8dcbf250b0587b48e885d03e4b74ba6744cd53b0535f64a0e291481

See more details on using hashes here.

File details

Details for the file django_encrypted_files-0.0.7-py3-none-any.whl.

File metadata

  • Download URL: django_encrypted_files-0.0.7-py3-none-any.whl
  • Upload date:
  • Size: 8.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.7.6

File hashes

Hashes for django_encrypted_files-0.0.7-py3-none-any.whl
Algorithm Hash digest
SHA256 bd71371c2ccb3898dc3124bd43b323c75a575594398495ed137ae0d94cd587a7
MD5 3af60b63865062f0843018cc8af3f05a
BLAKE2b-256 2d341929df914c1b9786057926640983d7f3d1a201479e06dae1f2d0c2e2e679

See more details on using hashes here.

Release history Release notifications | RSS feed

0.0.10

2 files

0.0.9

2 files

0.0.8

2 files

This release

0.0.7 This release

2 files

0.0.6

2 files

0.0.5

2 files

0.0.4

2 files

0.0.3

2 files

0.0.2

2 files

0.0.1

2 files

0.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page