"""AES-256-GCM encryption for the WhatsApp session stored in the database.""" from __future__ import annotations import base64 import hashlib import os from cryptography.hazmat.primitives.ciphers.aead import AESGCM PREFIX = "enc:v1:" class Sealer: def __init__(self, key: str): self._aes = AESGCM(hashlib.sha256(key.encode("utf-8")).digest()) def seal(self, data: bytes) -> str: nonce = os.urandom(12) ciphertext = self._aes.encrypt(nonce, data, None) return PREFIX + base64.b64encode(nonce + ciphertext).decode("ascii") def open(self, value: str) -> bytes: if not value.startswith(PREFIX): raise ValueError("stored session is not encrypted") raw = base64.b64decode(value[len(PREFIX):]) return self._aes.decrypt(raw[:12], raw[12:], None)