import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; export function generateDataKey() { return randomBytes(32); } export function encryptSecret(dataKey, plaintext) { const iv = randomBytes(12); const cipher = createCipheriv("aes-256-gcm", dataKey, iv); const ciphertext = Buffer.concat([ cipher.update(plaintext, "utf8"), cipher.final(), ]); const tag = cipher.getAuthTag(); return { ciphertext: ciphertext.toString("base64"), iv: iv.toString("base64"), tag: tag.toString("base64"), }; } export function decryptSecret(dataKey, value) { const decipher = createDecipheriv("aes-256-gcm", dataKey, Buffer.from(value.iv, "base64")); decipher.setAuthTag(Buffer.from(value.tag, "base64")); const plaintext = Buffer.concat([ decipher.update(Buffer.from(value.ciphertext, "base64")), decipher.final(), ]); return plaintext.toString("utf8"); } export function tamperCiphertext(value) { const bytes = Buffer.from(value.ciphertext, "base64"); if (bytes.length === 0) return { ...value, ciphertext: "AA==" }; bytes[bytes.length - 1] = (bytes[bytes.length - 1] ?? 0) ^ 0xff; return { ...value, ciphertext: bytes.toString("base64") }; } export function maskSecret(value) { if (value.length === 0) return "(empty)"; if (value.length <= 4) return "•".repeat(value.length); return `${value.slice(0, 2)}${"•".repeat(Math.min(10, value.length - 4))}${value.slice(-2)}`; } export function ciphertextBytes(value) { return (Buffer.from(value.ciphertext, "base64").length + Buffer.from(value.iv, "base64").length + Buffer.from(value.tag, "base64").length); } //# sourceMappingURL=crypto.js.map