const crypto = require('crypto'); const config = require('./config'); function getKey() { if (!config.crypto.secret) { throw new Error('APP_ENCRYPTION_SECRET 未配置'); } return crypto.createHash('sha256').update(String(config.crypto.secret)).digest(); } function encryptJson(value) { const plainText = JSON.stringify(value); const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', getKey(), iv); const encrypted = Buffer.concat([cipher.update(plainText, 'utf8'), cipher.final()]); const tag = cipher.getAuthTag(); const payloadHash = crypto.createHash('sha256').update(plainText).digest('hex'); return { ciphertext: encrypted.toString('base64'), iv: iv.toString('base64'), tag: tag.toString('base64'), payloadHash }; } function decryptJson(record) { const decipher = crypto.createDecipheriv( 'aes-256-gcm', getKey(), Buffer.from(record.iv, 'base64') ); decipher.setAuthTag(Buffer.from(record.tag, 'base64')); const decrypted = Buffer.concat([ decipher.update(Buffer.from(record.ciphertext, 'base64')), decipher.final() ]); return JSON.parse(decrypted.toString('utf8')); } function sha256(value) { return crypto.createHash('sha256').update(String(value || '')).digest('hex'); } module.exports = { encryptJson, decryptJson, sha256 };