Files
knur-app/lib/crypto.ts

34 lines
1.3 KiB
TypeScript
Raw Permalink Normal View History

2026-06-18 11:12:12 +02:00
import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
const ALGORITHM = "aes-256-gcm";
const IV_BYTES = 12;
const TAG_BYTES = 16;
function getKey(): Buffer {
const hex = process.env.GARMIN_ENCRYPTION_KEY;
if (!hex || hex.length !== 64) {
throw new Error("Brak lub nieprawidłowy GARMIN_ENCRYPTION_KEY w konfiguracji.");
}
return Buffer.from(hex, "hex");
}
export function encrypt(plaintext: string): string {
const key = getKey();
const iv = randomBytes(IV_BYTES);
const cipher = createCipheriv(ALGORITHM, key, iv);
const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
// Format: iv(hex):tag(hex):ciphertext(hex)
return `${iv.toString("hex")}:${tag.toString("hex")}:${encrypted.toString("hex")}`;
}
export function decrypt(stored: string): string {
const parts = stored.split(":");
if (parts.length !== 3) throw new Error("Nieprawidłowy format zaszyfrowanego hasła.");
const [ivHex, tagHex, dataHex] = parts;
const key = getKey();
const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(ivHex, "hex"));
decipher.setAuthTag(Buffer.from(tagHex, "hex"));
return decipher.update(Buffer.from(dataHex, "hex")).toString("utf8") + decipher.final("utf8");
}