openEncryption.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * encryptionFun()
  3. 示例1 http://xxx.com?id=123
  4. encryptionFun('id=123')
  5. 示例2 http://xxx.com {"id":123}
  6. encryptionFun('{"id":123}')
  7. 示例3 http://xxx.com?id=123&name=张三 {"id":123}
  8. encryptionFun('id=123&name=张三{"id":123}')
  9. */
  10. import { generateUUID } from "@/utils/index"
  11. import { sha256 } from 'js-sha256'
  12. /**
  13. *
  14. * @param { str } raw 参数用&隔开
  15. * @param { Object } body
  16. * @returns
  17. */
  18. // 替换无效编码序列(解决 decodeURIComponent 报错 "URI malformed" 的问题)
  19. export const decodeURIComponentSafe = (str) => {
  20. try {
  21. return decodeURIComponent(str);
  22. } catch (e) {
  23. // 替换无效的百分号编码为空字符串
  24. return decodeURIComponent(str.replace(/%(?![\da-f]{2})/gi, ''));
  25. }
  26. }
  27. export const encryptionFun = ({raw, body, appId, AppSecret, timestamp}) => {
  28. console.log(123, '->进入加密:', 456)
  29. const initSign = {
  30. appId,
  31. nonce: generateUUID(),
  32. timestamp,
  33. }
  34. const _initSignArr = Object.keys(initSign).map(key => {
  35. return `${key}=${initSign[key]}`
  36. })
  37. const _initSign = _initSignArr.join('&')
  38. const paramsStr = _initSign + AppSecret
  39. let str = ''
  40. if (raw) {
  41. str += decodeURIComponentSafe(raw)
  42. }
  43. if (body && Object.keys(body).length) {
  44. str += decodeURIComponentSafe(JSON.stringify(body))
  45. }
  46. return {
  47. ...initSign,
  48. sign: sha256(str + paramsStr)
  49. }
  50. }