UNPKG

godprotocol

Version:

A distributed computing environment for Web 4.0 — integrating AI, decentralisation, and virtual computation.

55 lines (41 loc) 1.51 kB
import crypto, { createHash, randomBytes, createCipheriv } from "crypto"; const deriveKey = (secret) => createHash("sha256").update(String(secret)).digest(); /** * Encrypt a value (usually a session token) using AES-256-GCM. * Returns a compact base64 string encoding iv|authTag|ciphertext. */ const decryptToken = (enc, secret) => { if (!enc) return null; try { const key = deriveKey(secret); const parts = enc.split(":"); if (parts.length < 3) throw new Error("Invalid token format"); const iv = Buffer.from(parts[0], "base64"); const tag = Buffer.from(parts[1], "base64"); const data = Buffer.from(parts.slice(2).join(":"), "base64"); const decipher = createDecipheriv("aes-256-gcm", key, iv); decipher.setAuthTag(tag); const decrypted = Buffer.concat([ decipher.update(data), decipher.final(), ]).toString("utf8"); return JSON.parse(decrypted); } catch (err) { console.error("❌ Decrypt failed:", err.message); return null; } }; const encryptToken = (payload, secret) => { const key = deriveKey(secret); const iv = randomBytes(12); // GCM standard const cipher = createCipheriv("aes-256-gcm", key, iv); const encrypted = Buffer.concat([ cipher.update(JSON.stringify(payload), "utf8"), cipher.final(), ]); const tag = cipher.getAuthTag(); // iv:tag:data return `${iv.toString("base64")}:${tag.toString("base64")}:${encrypted.toString("base64")}`; }; export { encryptToken, decryptToken };