openEncryption.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. const initSign = {
  29. appId,
  30. nonce: generateUUID(),
  31. timestamp,
  32. }
  33. const _initSignArr = Object.keys(initSign).map(key => {
  34. return `${key}=${initSign[key]}`
  35. })
  36. const _initSign = _initSignArr.join('&')
  37. const paramsStr = _initSign + AppSecret
  38. let str = ''
  39. if (raw) {
  40. str += decodeURIComponentSafe(raw)
  41. }
  42. if (body && Object.keys(body).length) {
  43. str += decodeURIComponentSafe(JSON.stringify(body))
  44. }
  45. return {
  46. ...initSign,
  47. sign: sha256(str + paramsStr)
  48. }
  49. }