SPB Git forge

spb/spb-cloud

Public
10commits 1branches 0releases
3.2 MBsize
maindefault branch
1 h agolast push
JavaScript 56.7% TypeScript 42.6%
1.1 KB · 27 lines typescript
Raw Blame History
1import { createCipheriv, createDecipheriv, randomBytes } from "crypto";23const ALGORITHM = "aes-256-gcm";4const KEY = Buffer.from(5  (process.env.ENCRYPTION_KEY || "spb-private-cloud-encrypt-key32!!").padEnd(32, "0").slice(0, 32)6);78export function encrypt(text: string): string {9  const iv = randomBytes(12);10  const cipher = createCipheriv(ALGORITHM, KEY, iv);11  const encrypted = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]);12  const tag = cipher.getAuthTag();13  return `${iv.toString("hex")}:${tag.toString("hex")}:${encrypted.toString("hex")}`;14}1516export function decrypt(data: string): string {17  const parts = data.split(":");18  if (parts.length !== 3) throw new Error("Invalid encrypted data");19  const [ivHex, tagHex, encryptedHex] = parts;20  const iv = Buffer.from(ivHex, "hex");21  const tag = Buffer.from(tagHex, "hex");22  const encrypted = Buffer.from(encryptedHex, "hex");23  const decipher = createDecipheriv(ALGORITHM, KEY, iv);24  decipher.setAuthTag(tag);25  return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");26}27