2024-06-10 21:16:39 +02:00
|
|
|
import crypto from "crypto";
|
|
|
|
|
|
2025-01-14 19:03:38 +01:00
|
|
|
import { env } from "../env";
|
2024-10-03 19:59:44 +02:00
|
|
|
|
2024-06-10 21:16:39 +02:00
|
|
|
const algorithm = "aes-256-cbc"; //Using AES encryption
|
2024-10-03 19:59:44 +02:00
|
|
|
|
2024-12-31 11:30:29 +01:00
|
|
|
// We fallback to a key of 0s if the key was not provided because env validation was skipped
|
|
|
|
|
// This should only be the case in CI
|
|
|
|
|
const key = Buffer.from(env.SECRET_ENCRYPTION_KEY || "0".repeat(64), "hex");
|
2024-06-10 21:16:39 +02:00
|
|
|
|
|
|
|
|
export function encryptSecret(text: string): `${string}.${string}` {
|
|
|
|
|
const initializationVector = crypto.randomBytes(16);
|
|
|
|
|
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), initializationVector);
|
|
|
|
|
let encrypted = cipher.update(text);
|
|
|
|
|
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
|
|
|
|
return `${encrypted.toString("hex")}.${initializationVector.toString("hex")}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function decryptSecret(value: `${string}.${string}`) {
|
2024-12-15 15:40:26 +01:00
|
|
|
return decryptSecretWithKey(value, key);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function decryptSecretWithKey(value: `${string}.${string}`, key: Buffer) {
|
2024-06-10 21:16:39 +02:00
|
|
|
const [data, dataIv] = value.split(".") as [string, string];
|
|
|
|
|
const initializationVector = Buffer.from(dataIv, "hex");
|
|
|
|
|
const encryptedText = Buffer.from(data, "hex");
|
|
|
|
|
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), initializationVector);
|
|
|
|
|
let decrypted = decipher.update(encryptedText);
|
|
|
|
|
decrypted = Buffer.concat([decrypted, decipher.final()]);
|
|
|
|
|
return decrypted.toString();
|
|
|
|
|
}
|