【前端开发】随机密钥加密解密--修改request.js和cryptoJsUtil.js脚本

This commit is contained in:
liyuetong
2021-10-25 09:55:05 +08:00
parent 4c17dfafc8
commit 63606aff2f
4 changed files with 90 additions and 9 deletions

View File

@@ -1,8 +1,16 @@
import axios from 'axios'
import AESTools from '@/assets/js/utils/cryptoJsUtil'
// import AESTools from '@/assets/js/utils/cryptoJsUtil'
import {
MD5,
RSAEncrypt,
AESEncrypt,
AESDecrypt,
randomString,
publicKey,
} from '@/assets/js/utils/cryptoJsUtil'
import configApp from '@/config'
import { Dialog, Toast } from 'vant'
import MD5 from 'js-md5'
// import MD5 from 'js-md5'
import CacheUtils from '@/assets/js/utils/cacheUtils'
import BusinessCommon from '@/assets/js/business-common'
@@ -147,16 +155,42 @@ service.interceptors.request.use(
message: '加载中……'
})
}
// 生成本次请求随机密钥
let masterKey
if (!window.localStorage.getItem('masterKey')) {
masterKey = randomString();
window.localStorage.setItem('masterKey',masterKey)
} else {
masterKey = window.localStorage.getItem('masterKey')
}
/**
* 请求拦截处理(待添加 判断走统一网关处理)
*/
console.log(config)
if (config.url && /api\/$/.test(config.url.split(configApp.API_VERSION)[0]) && configApp.API_VERSION == 'v2') {
if (!config.data || config.data == null) {
config.data = {}
}
if (!!config.data && config.data != null) {
let encrypt = AESTools.AESEncrypt(JSON.stringify(config.data), configApp.REQ_PWD)
config.data = { data: encrypt }
// let encrypt = AESTools.AESEncrypt(JSON.stringify(config.data), configApp.REQ_PWD)
console.log('随机密钥:' + masterKey);
// RSA加密随机密钥
let ak = RSAEncrypt(masterKey, publicKey);
console.log('加密后的masterKey' + ak);
// 随机密钥加密data
let data = AESEncrypt(JSON.stringify(config.data), masterKey);
console.log('MD5值' + MD5(AESEncrypt(data, masterKey)).toString());
// 验证数据完整性MD5
// 数据完整性MD5需要进行二次AES加密
config.headers['signature'] = MD5(AESEncrypt(data, masterKey)).toString();
config.data = { ak, data };
console.log(config.data);
if(AESDecrypt(config.data.data, masterKey)){
console.log(JSON.parse(AESDecrypt(config.data.data, masterKey)));
}else{
console.log(AESDecrypt(config.data.data, masterKey));
}
// config.data = { data: encrypt }
}
}
@@ -208,7 +242,19 @@ service.interceptors.response.use(
) {
if (res.response) {
// 正常情況返回必有response 节点
res = JSON.parse(AESTools.AESDecrypt(res.response, configApp.REQ_PWD))
// 返回结果的随机密钥
let masterKey;
if (!window.localStorage.getItem('masterKey')) {
return Promise.reject('密钥失效')
} else {
masterKey = window.localStorage.getItem('masterKey');
}
console.log('请求结果response' + response)
console.log('请求结果masterKey' + masterKey)
console.log(JSON.parse(AESDecrypt(response.data.response, masterKey)))
// 使用随机密钥解密返回结果data
res = JSON.parse(AESDecrypt(res.response, masterKey))
// res = JSON.parse(AESTools.AESDecrypt(res.response, configApp.REQ_PWD))
}
}