JavaScript 56.7%
TypeScript 42.6%
1import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "crypto";23// Chiffrement de CONTENU de fichiers au repos (AES-256-GCM).4// Clé dédiée FILE_ENCRYPTION_KEY (≠ ENCRYPTION_KEY du gestionnaire de mots de passe).5// Format auto-porté : [iv(12) | authTag(16) | ciphertext] — pas besoin de stocker l'IV en base.67const ALGORITHM = "aes-256-gcm";8const IV_LEN = 12;9const TAG_LEN = 16;1011let cachedKey: Buffer | null = null;12function getKey(): Buffer {13 if (cachedKey) return cachedKey;14 const master =15 process.env.FILE_ENCRYPTION_KEY ||16 process.env.ENCRYPTION_KEY ||17 "default-encryption-key-change-me!";18 cachedKey = scryptSync(master, "spb-cloud-file-salt", 32);19 return cachedKey;20}2122export function encryptBuffer(plain: Buffer): Buffer {23 const iv = randomBytes(IV_LEN);24 const cipher = createCipheriv(ALGORITHM, getKey(), iv);25 const enc = Buffer.concat([cipher.update(plain), cipher.final()]);26 const tag = cipher.getAuthTag();27 return Buffer.concat([iv, tag, enc]);28}2930export function decryptBuffer(data: Buffer): Buffer {31 const iv = data.subarray(0, IV_LEN);32 const tag = data.subarray(IV_LEN, IV_LEN + TAG_LEN);33 const enc = data.subarray(IV_LEN + TAG_LEN);34 const decipher = createDecipheriv(ALGORITHM, getKey(), iv);35 decipher.setAuthTag(tag);36 return Buffer.concat([decipher.update(enc), decipher.final()]);37}38