import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto"; import { UnauthorizedException } from "@nestjs/common"; const ALGORITHM = "aes-256-gcm"; export function encryptionKey(): Buffer { const value = process.env.MINIAPP_CREDENTIAL_ENCRYPTION_KEY ?? process.env.SESSION_SECRET; if (!value || value.length < 32) throw new UnauthorizedException("小程序凭据加密密钥未正确配置"); return createHash("sha256").update(value).digest(); } export function encryptMiniAppCredential(plaintext: string): { ciphertext: string; iv: string; authTag: string; algorithm: string; } { const iv = randomBytes(12); const cipher = createCipheriv(ALGORITHM, encryptionKey(), iv); const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]); return { algorithm: ALGORITHM, ciphertext: ciphertext.toString("base64"), iv: iv.toString("base64"), authTag: cipher.getAuthTag().toString("base64"), }; } export function decryptMiniAppCredential(value: unknown): string { const payload = value && typeof value === "object" && !Array.isArray(value) ? (value as Record) : null; if ( !payload || payload.algorithm !== ALGORITHM || typeof payload.ciphertext !== "string" || typeof payload.iv !== "string" || typeof payload.authTag !== "string" ) throw new UnauthorizedException("小程序凭据不可用"); const decipher = createDecipheriv(ALGORITHM, encryptionKey(), Buffer.from(payload.iv, "base64")); decipher.setAuthTag(Buffer.from(payload.authTag, "base64")); return Buffer.concat([ decipher.update(Buffer.from(payload.ciphertext, "base64")), decipher.final(), ]).toString("utf8"); }