安装 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'
// 解密 data:要加密解密的数据,AES_KEY:密钥,IV:偏移量
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();

/*
* 这种格式转换会报错: Malformed UTF-8 data
* bytes.toString(CryptoJS.enc.Utf8)
*
* CryptoJS.enc.Utf8.stringify(decrypt).toString()
* */

// Decrypt
// let bytes = CryptoJS.AES.decrypt(data, keyStr, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
//
// let decryptData1 = CryptoJS.enc.Utf8.stringify(bytes).toString()
// console.log('decryptData1', decryptData1)

// let decryptedDat2 = bytes.toString(CryptoJS.enc.Utf8);
// console.log('decryptedDat2', decryptedDat2)
// replaceJsonLongTranStr(jsonSubstringFragment(this.currentRow.content))

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 => {
// typeof response.data.data === 'string' && response.data.data.length > 200
// 判断 是否为 加密 数据
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
} //...