import crypto from 'node:crypto' import { CIPHER_KEY } from './config.mjs' /** * 登录口令加密 —— 与 web/src/utils/cipher.ts 的 CryptoJS 实现逐位等价: * md5(plain) 的十六进制字符串 → AES-256-ECB/Pkcs7(key = md5(CIPHER_KEY) 的 32 字节 UTF8)→ 密文 hex * * 这里用 Node 内置 crypto 复刻,避免为一个函数拖进 crypto-js。 * 自检值见 selfTest(),与前端注释里的期望完全一致。 */ export function md5Hex(str) { return crypto.createHash('md5').update(str, 'utf8').digest('hex') } export function encryptPassword(plain) { // md5(CIPHER_KEY) 是 32 个十六进制字符,按 UTF8 取字节正好 32 字节 = AES-256 的密钥长度 const key = Buffer.from(md5Hex(CIPHER_KEY), 'utf8') const cipher = crypto.createCipheriv('aes-256-ecb', key, null) cipher.setAutoPadding(true) // Pkcs7 return Buffer.concat([cipher.update(md5Hex(plain), 'utf8'), cipher.final()]).toString('hex') } const EXPECT_123456 = 'd4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b' /** 启动时自检:加密链路和后端对不上的话,344 条用例会全军覆没在登录这一步,早失败早知道 */ export function selfTest() { const got = encryptPassword('123456') if (got !== EXPECT_123456) { throw new Error(`口令加密自检失败:期望 ${EXPECT_123456},实际 ${got}(CIPHER_KEY 是否被改过?)`) } return true }