import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "crypto"; // Chiffrement de CONTENU de fichiers au repos (AES-256-GCM). // Clé dédiée FILE_ENCRYPTION_KEY (≠ ENCRYPTION_KEY du gestionnaire de mots de passe). // Format auto-porté : [iv(12) | authTag(16) | ciphertext] — pas besoin de stocker l'IV en base. const ALGORITHM = "aes-256-gcm"; const IV_LEN = 12; const TAG_LEN = 16; let cachedKey: Buffer | null = null; function getKey(): Buffer { if (cachedKey) return cachedKey; const master = process.env.FILE_ENCRYPTION_KEY || process.env.ENCRYPTION_KEY || "default-encryption-key-change-me!"; cachedKey = scryptSync(master, "spb-cloud-file-salt", 32); return cachedKey; } export function encryptBuffer(plain: Buffer): Buffer { const iv = randomBytes(IV_LEN); const cipher = createCipheriv(ALGORITHM, getKey(), iv); const enc = Buffer.concat([cipher.update(plain), cipher.final()]); const tag = cipher.getAuthTag(); return Buffer.concat([iv, tag, enc]); } export function decryptBuffer(data: Buffer): Buffer { const iv = data.subarray(0, IV_LEN); const tag = data.subarray(IV_LEN, IV_LEN + TAG_LEN); const enc = data.subarray(IV_LEN + TAG_LEN); const decipher = createDecipheriv(ALGORITHM, getKey(), iv); decipher.setAuthTag(tag); return Buffer.concat([decipher.update(enc), decipher.final()]); }