crypto.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const CryptoJS = require("crypto-js");
  2. export const Base64 = (content) => {
  3. const words = CryptoJS.enc.Utf8.parse(content);
  4. const base64Str = CryptoJS.enc.Base64.stringify(words);
  5. return base64Str;
  6. };
  7. export const AES = (content) => {
  8. const KEY = "Qmth87863577qmth";
  9. // const IV = "1234567890123456";
  10. const key = CryptoJS.enc.Utf8.parse(KEY);
  11. // const iv = CryptoJS.enc.Utf8.parse(IV);
  12. const encrypted = CryptoJS.AES.encrypt(content, key, {
  13. // iv: iv,
  14. mode: CryptoJS.mode.ECB,
  15. padding: CryptoJS.pad.Pkcs7,
  16. });
  17. return encrypted.toString();
  18. };
  19. export const AESDecode = (content) => {
  20. const KEY = "Qmth87863577qmth";
  21. // const IV = "1234567890123456";
  22. const key = CryptoJS.enc.Utf8.parse(KEY);
  23. // const iv = CryptoJS.enc.Utf8.parse(IV);
  24. const decrypted = CryptoJS.AES.decrypt(content, key, {
  25. // iv: iv,
  26. mode: CryptoJS.mode.ECB,
  27. padding: CryptoJS.pad.Pkcs7,
  28. });
  29. return decrypted.toString(CryptoJS.enc.Utf8);
  30. };
  31. /**
  32. * 获取authorisation
  33. * @param {Object} infos 相关信息
  34. * @param {String} type 类别:secret、token两种
  35. */
  36. export const getAuthorization = (infos, type) => {
  37. // {type} {invoker}:base64(sha1(method&uri&timestamp&{secret}))
  38. if (type === "secret") {
  39. // accessKey | method&uri&timestamp&accessSecret
  40. const str = `${infos.method.toLowerCase()}&${infos.uri}&${
  41. infos.timestamp
  42. }&${infos.accessSecret}`;
  43. const sign = CryptoJS.enc.Base64.stringify(CryptoJS.SHA1(str));
  44. return `Secret ${infos.accessKey}:${sign}`;
  45. } else if (type === "token") {
  46. // userId | method&uri&timestamp&token
  47. const str = `${infos.method.toLowerCase()}&${infos.uri}&${
  48. infos.timestamp
  49. }&${infos.token}`;
  50. const sign = CryptoJS.enc.Base64.stringify(CryptoJS.SHA1(str));
  51. return `Token ${infos.account}:${sign}`;
  52. }
  53. };