From a6fc088599ae85f4aae13c5e154310679ed2a8ce Mon Sep 17 00:00:00 2001 From: nocci Date: Sat, 6 Dec 2025 13:39:03 +0000 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(utils):=20enhance?= =?UTF-8?q?=20encryption=20key=20handling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add base64 and hashlib imports for key derivation - improve key validation to accept passphrase or full key - handle exceptions during Fernet key creation for robustness --- app/utils.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/app/utils.py b/app/utils.py index 774905e..afd67de 100644 --- a/app/utils.py +++ b/app/utils.py @@ -1,3 +1,5 @@ +import base64 +import hashlib import os import secrets from typing import Optional @@ -10,11 +12,17 @@ _ENC_KEY = os.getenv("ENCRYPTION_KEY") _f = None if _ENC_KEY: - # If the key is already a valid Fernet key string, use it directly. - # Otherwise you could do more validation/derivation, but for now we assume a proper key. - _f = Fernet( - _ENC_KEY.encode() if not _ENC_KEY.strip().endswith("=") else _ENC_KEY - ) + try: + key_str = _ENC_KEY.strip() + # Accept either a full Fernet key or derive one from an arbitrary passphrase. + if len(key_str) >= 44 and key_str.endswith("="): + fernet_key = key_str.encode() + else: + digest = hashlib.sha256(key_str.encode("utf-8")).digest() + fernet_key = base64.urlsafe_b64encode(digest) + _f = Fernet(fernet_key) + except Exception: + _f = None def can_encrypt() -> bool: