Files
Mebbling/lib/crypto.ts
T

17 lines
900 B
TypeScript

import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
function key() {
const value = process.env.TOKEN_ENCRYPTION_KEY;
if (!value || !/^[0-9a-f]{64}$/i.test(value)) throw new Error("TOKEN_ENCRYPTION_KEY must be 64 hexadecimal characters");
return Buffer.from(value, "hex");
}
export function encrypt(value: string) {
const iv = randomBytes(12); const cipher = createCipheriv("aes-256-gcm", key(), iv);
const body = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
return Buffer.concat([iv, cipher.getAuthTag(), body]).toString("base64url");
}
export function decrypt(value: string) {
const raw = Buffer.from(value, "base64url"); const decipher = createDecipheriv("aes-256-gcm", key(), raw.subarray(0, 12));
decipher.setAuthTag(raw.subarray(12, 28)); return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8");
}