安装 crypto-js
1
| npm install crypto-js --save
|
新建 utils/crypto.js
replaceJsonLongTranStr 用来处理 JSON str 整数长度精度丢失问题!
AES_KEY 后端约束的 Key ,或者自己定义的 Key!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import CryptoJS from 'crypto-js'; import { jsonSubstringFragment, replaceJsonLongTranStr } from '@/utils/index'
export function decrypt(data, AES_KEY, IV) { let keyStr = AES_KEY ? AES_KEY : '1234567887654321'; let key = CryptoJS.enc.Utf8.parse(keyStr); let decrypt = CryptoJS.AES.decrypt(data, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); let decryptData = CryptoJS.enc.Utf8.stringify(decrypt).toString();
return JSON.parse(replaceJsonLongTranStr(decryptData)); }
export function encrypt(data, AES_KEY, IV) { const key = CryptoJS.enc.Utf8.parse(AES_KEY); const iv = CryptoJS.enc.Utf8.parse(IV); const encrypted = CryptoJS.AES.encrypt(data, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, }); return encrypted.toString(); }
|
使用
这里用了 axios 拦截器,只展示了部分代码,拦截了后端部分接口传递的为加密数据,在此需要通过CryptoJS来进行解密!
1234567887654321 这个为 后端约束的 key!
1 2 3 4 5 6 7 8 9 10
| service.interceptors.response.use(response => { if (typeof response.data.data === 'string' && response.data.data.length > 200 ){ response.data.data = decrypt(response.data.data, '1234567887654321') console.log('in response', response.data) return response.data } return response }
|