2025-04-14 20:56:45 -04:00
|
|
|
import * as crypto from "crypto";
|
|
|
|
|
|
|
|
const ALGORITHM = "aes-256-gcm";
|
|
|
|
|
|
|
|
export function encrypt(value: string, key: string): string {
|
|
|
|
const iv = crypto.randomBytes(12);
|
2025-04-16 22:39:24 -04:00
|
|
|
const keyBuffer = Buffer.from(key, "base64"); // assuming base64 input
|
|
|
|
|
|
|
|
const cipher = crypto.createCipheriv(ALGORITHM, keyBuffer, iv);
|
2025-04-14 20:56:45 -04:00
|
|
|
|
|
|
|
const encrypted = Buffer.concat([
|
|
|
|
cipher.update(value, "utf8"),
|
|
|
|
cipher.final()
|
|
|
|
]);
|
|
|
|
const authTag = cipher.getAuthTag();
|
|
|
|
|
|
|
|
return [
|
|
|
|
iv.toString("base64"),
|
|
|
|
encrypted.toString("base64"),
|
|
|
|
authTag.toString("base64")
|
|
|
|
].join(":");
|
|
|
|
}
|
|
|
|
|
|
|
|
export function decrypt(encryptedValue: string, key: string): string {
|
|
|
|
const [ivB64, encryptedB64, authTagB64] = encryptedValue.split(":");
|
|
|
|
|
|
|
|
const iv = Buffer.from(ivB64, "base64");
|
|
|
|
const encrypted = Buffer.from(encryptedB64, "base64");
|
|
|
|
const authTag = Buffer.from(authTagB64, "base64");
|
2025-04-16 22:39:24 -04:00
|
|
|
const keyBuffer = Buffer.from(key, "base64");
|
2025-04-14 20:56:45 -04:00
|
|
|
|
2025-04-16 22:39:24 -04:00
|
|
|
const decipher = crypto.createDecipheriv(ALGORITHM, keyBuffer, iv);
|
2025-04-14 20:56:45 -04:00
|
|
|
decipher.setAuthTag(authTag);
|
|
|
|
|
|
|
|
const decrypted = Buffer.concat([
|
|
|
|
decipher.update(encrypted),
|
|
|
|
decipher.final()
|
|
|
|
]);
|
|
|
|
return decrypted.toString("utf8");
|
|
|
|
}
|