const isJSON = require('is-json') const CryptoJS = require('crypto-js') const keyHex = process.env.AES function encode (payload, timestamp = 0) { const data = { payload, expired_timestamp: timestamp ? timestamp + Date.now() : 0, } const messageHex = CryptoJS.enc.Utf8.parse(JSON.stringify(data)) var encrypted = CryptoJS.AES.encrypt(messageHex, keyHex, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, }) return encrypted.toString() } function decode (encrypted) { const errmsg = '登录凭证无效' try{ var decrypt = CryptoJS.enc.Utf8.stringify( CryptoJS.AES.decrypt(encrypted, keyHex, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, }), ) }catch(err) { throw new Error(errmsg) } if(!isJSON(decrypt)) { throw new Error(errmsg) } var payload = JSON.parse(decrypt) if (!payload.payload) { throw new Error(errmsg) } if (Date.now() >= payload.expired_timestamp) { throw new Error('登录凭证已过期') } return payload.payload } module.exports = { encode, decode }