Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 1 min read

Encrypting users' files and deleting them automatically

On an audio-analysis SaaS that I designed solo, users' files are encrypted, then deleted automatically. The best way to protect those files: keep them encrypted for as long as they exist, and keep them for as short a tim

On an audio-analysis SaaS that I designed solo, users' files are encrypted, then deleted automatically. The best way to protect those files: keep them encrypted for as long as they exist, and keep them for as short a time as possible.

Here are the principles for a service like this.

Encrypt with an authenticated method. It guarantees two things: nobody reads without the key, and nobody modifies without it showing. In Python, Fernet (from the cryptography library) does it with AES 128 and HMAC SHA256:

from cryptography.fernet import Fernet

f = Fernet(KEY)            # key read from the environment, never from code
token = f.encrypt(data)
data = f.decrypt(token)

Two clarifications. The key must stay secret: anyone who has it can create and read messages. And Fernet is built for data that fits in memory: its documentation calls it unsuitable for very large files. For large audio files, you need to encrypt in blocks.

Delete with a scheduled task. A regular task erases any file older than the retention period. Two rules make it reliable:

def cleanup(now):
    for rec in expired_records(now):
        storage.delete(rec.path)   # the file first
        db.delete(rec)             # then the row
  • The file before the row. If the task stops between the two, the record is found again on the next run and the work resumes. In the other order, an orphan file would stay and nobody would know.
  • Being able to rerun it safely. Replaying the task must break nothing.

One last point: the retention period is a promise made to the user. You might as well write it on the page, and keep it.

Amine Affif, full-stack developer in Paris. amineaffif.com

๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.