Skip to content

Instantly share code, notes, and snippets.

@dmendiza
Created July 15, 2015 15:32
Show Gist options
  • Save dmendiza/8af9a80f1a4a8c04c831 to your computer and use it in GitHub Desktop.
Save dmendiza/8af9a80f1a4a8c04c831 to your computer and use it in GitHub Desktop.
# Generate a new fernet key and save it to a file named encryption_key.txt
>>> from cryptography.fernet import Fernet
>>> Fernet.generate_key()
# Load key from file in app.py
with open(encryption_key.txt) as f:
FERNET_KEY = f.read()
# In the upload function, we want to encrypt the file
@app.route("/upload", methods=["POST"])
@login.login_required
def upload():
file = request.files['file_data']
encryptor = Fernet(FERNET_KEY)
token = encryptor.encrypt(file.stream.read())
if file:
ef = EncryptedFile(
login.current_user.id,
token,
file.filename,
file.mimetype
)
db.session.add(ef)
db.session.commit()
return "Saved. <a href='/download/{0}'>Download here</a>".format(ef.id)
# and we also want to decrypt it in the download function
@app.route("/download/<file_id>")
@login.login_required
def download(file_id):
query = EncryptedFile.query.filter_by(
id=file_id,
user_id=login.current_user.id,
)
result = query.first()
if not result:
return "Invalid"
else:
decryptor = Fernet(FERNET_KEY)
decrypted_data = decryptor.decrypt(result.payload)
resp = Response(
decrypted_data,
status=200,
mimetype=result.mime_type
)
resp.headers["Content-Disposition"] = (
'attachment; filename="{0}"'.format(result.file_name)
)
return resp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment