Files
persionalBrand/apps/api/src/miniapp-credential-crypto.ts
T
que01 d0a0eeea8c
CI / Browser smoke (pull_request) Successful in 58s
CI / Static checks (pull_request) Successful in 1m32s
CI / API integration (pull_request) Successful in 1m27s
CI / Production build (pull_request) Successful in 2m7s
feat: 支持按品牌配置微信登录凭据
2026-10-23 22:07:39 +08:00

49 lines
1.7 KiB
TypeScript

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<string, unknown>)
: 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");
}