This commit is contained in:
Dominik Klarkowski
2026-06-18 11:12:12 +02:00
parent 047e580da0
commit 115d56cd12
2 changed files with 36 additions and 2 deletions

33
lib/crypto.ts Normal file
View File

@@ -0,0 +1,33 @@
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");
}