openEncryption.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { generateUUID } from "@/utils/index"
  2. import { sha256 } from 'js-sha256'
  3. import qs from 'qs'
  4. // 加密方式:请求头加参数: appId + nonce + timestamp + sign
  5. // (sign为: queryJsonData+paramsToStrSort+appSecret拼接后sha256加密字符串)
  6. // 开启参数加密
  7. export const encryptionFun = (config) => {
  8. // console.log('加密内容用完请注释->config', config)
  9. const initSign = {
  10. appId: 'web_client', // 与后端协商一致使用
  11. nonce: generateUUID(), // 前端生成唯一参数
  12. timestamp: new Date().getTime() + 1000,
  13. }
  14. // 固定的参数初始化成字符串
  15. const paramsToStrSort = ['appId', 'nonce', 'timestamp'] // 顺序不能变
  16. let paramsStr = paramsToStrSort.reduce((str, key) => {
  17. if (initSign[key]) str = str ? str + `&${key}=${initSign[key]}` : `${key}=${initSign[key]}`
  18. return str
  19. }, '')
  20. const appSecret = 'fa0fc0b5098b974b' // 与后端协商一致使用(拼接在paramsStr后面,且拼接时不加key)
  21. paramsStr = paramsStr + appSecret
  22. // console.log('加密内容用完请注释->paramsStr', paramsStr)
  23. // 请求的参数json // 携带的参数json一下,url拼接参数的直接用,没有参数不拼接
  24. const queryJsonData = config.data && Object.keys(config.data).length ?
  25. decodeURIComponent(JSON.stringify(sortObjectByKey(config.data))) : config.params && Object.keys(config.params).length ?
  26. decodeURIComponent(qs.stringify(sortObjectByKey(config.params), { allowDots: true }) ): config.url.split('?')?.length>1 ?
  27. config.url.split('?')[1] : ''
  28. // sha256加密字符串
  29. if (paramsStr) initSign.sign = sha256(queryJsonData + paramsStr)
  30. // console.log('加密内容用完请注释->queryJsonData', queryJsonData)
  31. // 请求头加参数initSign,请求头加参数: appId + nonce + timestamp + sign
  32. if (initSign && Object.keys(initSign).length) Object.keys(initSign).forEach(key => { (config).header[key] = initSign[key] })
  33. }
  34. function sortObjectByKey(obj) {
  35. return obj
  36. // return Object.keys(obj)
  37. // .sort()
  38. // .reduce((sortedObj, key) => {
  39. // sortedObj[key] = obj[key];
  40. // return sortedObj;
  41. // }, {});
  42. }