import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'; import { env } from '../env'; const key = Buffer.from(env.TOKEN_ENCRYPTION_KEY, 'base64'); /** AES-256-GCM. Output: base64(iv | tag | ciphertext). */ export function encrypt(plaintext: string): string { const iv = randomBytes(12); const cipher = createCipheriv('aes-256-gcm', key, iv); const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]); return Buffer.concat([iv, cipher.getAuthTag(), ct]).toString('base64'); } export function decrypt(payload: string): string { const buf = Buffer.from(payload, 'base64'); const decipher = createDecipheriv('aes-256-gcm', key, buf.subarray(0, 12)); decipher.setAuthTag(buf.subarray(12, 28)); return Buffer.concat([decipher.update(buf.subarray(28)), decipher.final()]).toString('utf8'); } export const sha256 = (s: string) => createHash('sha256').update(s).digest('hex'); export const randomToken = (bytes = 32) => randomBytes(bytes).toString('base64url');