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

45 lines
1.8 KiB
TypeScript

import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
const ALGORITHMUS = "aes-256-gcm";
const IV_LAENGE = 12;
const TAG_LAENGE = 16;
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(IV_LAENGE);
const cipher = createCipheriv(ALGORITHMUS, schluessel(), iv, { authTagLength: TAG_LAENGE });
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 ivBytes = Buffer.from(iv, "base64");
const tagBytes = Buffer.from(tag, "base64");
// Node akzeptiert sonst gekuerzte GCM-Tags; Laengen daher fest vorgeben.
if (ivBytes.length !== IV_LAENGE || tagBytes.length !== TAG_LAENGE) {
throw new Error("Unbekanntes Format des verschluesselten SMTP-Passworts");
}
const decipher = createDecipheriv(ALGORITHMUS, schluessel(), ivBytes, { authTagLength: TAG_LAENGE });
decipher.setAuthTag(tagBytes);
return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8");
}