Files
PecHub/worker/app/security.py
T
2026-06-18 11:24:05 +02:00

39 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Modulo sicurezza worker decifratura credenziali AES-256-GCM.
Replica solo le funzioni necessarie al worker (decrypt_credential).
La chiave di cifratura viene letta dalla variabile d'ambiente ENCRYPTION_KEY
tramite WorkerSettings (stesso valore del backend).
Formato storage: base64(nonce_12byte || ciphertext || tag_16byte)
"""
import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from app.config import get_settings
settings = get_settings()
def decrypt_credential(encrypted: str) -> str:
"""
Decifra una stringa cifrata con AES-256-GCM.
Compatibile con encrypt_credential() del backend (stesso formato).
Solleva ValueError se la decifratura fallisce.
"""
key = settings.encryption_key_bytes
aesgcm = AESGCM(key)
try:
raw = base64.b64decode(encrypted.encode("ascii"))
nonce = raw[:12]
ciphertext_with_tag = raw[12:]
plaintext_bytes = aesgcm.decrypt(nonce, ciphertext_with_tag, None)
return plaintext_bytes.decode("utf-8")
except Exception as e:
raise ValueError(f"Decifratura credenziale fallita: {e}") from e