1
0
Fork 0
fahrPool/web/lib/firma/smtp-crypto.ts

37 lines
1.4 KiB
TypeScript

import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
const ALGORITHMUS = "aes-256-gcm";
function schluessel(): Buffer {
const roh = process.env.SMTP_VERSCHLUESSELUNG_KEY;
if (!roh) {
throw new Error("SMTP_VERSCHLUESSELUNG_KEY ist nicht gesetzt");
}
const key = Buffer.from(roh, "base64");
if (key.length !== 32) {
throw new Error("SMTP_VERSCHLUESSELUNG_KEY muss 32 Byte (base64) lang sein");
}
return key;
}
// Format v1:<iv>:<tag>:<ciphertext>, alles base64. Die Version erlaubt einen
// spaeteren Schluesselwechsel ohne Raten.
export function verschluessele(klartext: string): string {
const iv = randomBytes(12);
const cipher = createCipheriv(ALGORITHMUS, schluessel(), iv);
const ciphertext = Buffer.concat([cipher.update(klartext, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return ["v1", iv.toString("base64"), tag.toString("base64"), ciphertext.toString("base64")].join(":");
}
export function entschluessele(wert: string): string {
const teile = wert.split(":");
if (teile.length !== 4 || teile[0] !== "v1") {
throw new Error("Unbekanntes Format des verschluesselten SMTP-Passworts");
}
const [, iv, tag, ciphertext] = teile;
const decipher = createDecipheriv(ALGORITHMUS, schluessel(), Buffer.from(iv, "base64"));
decipher.setAuthTag(Buffer.from(tag, "base64"));
return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8");
}