encryption.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // 按需引入 CryptoJS 需要的组件
  2. const CryptoJS = require("crypto-js/core");
  3. const Latin1 = require("crypto-js/enc-latin1");
  4. const AES = require("crypto-js/aes");
  5. const ZeroPadding = require("crypto-js/pad-zeropadding");
  6. const Utf8 = require("crypto-js/enc-utf8");
  7. const Base64 = require("crypto-js/enc-base64");
  8. /*
  9. * 加密 解密
  10. */
  11. const baseCryptoCode = "1234veterans4321"; // 这个私钥每个项目指定一个唯一。更换密钥,请确认16位
  12. const getKeyHex = (cryptoCode) => Latin1.parse(cryptoCode || baseCryptoCode);
  13. const getIvHex = () => Latin1.parse(baseCryptoCode);
  14. /**
  15. * 加密
  16. * @param {String} key
  17. * @param {String} cryptoCode
  18. * @returns {string}
  19. */
  20. export const getEncrypt = (key, cryptoCode) => {
  21. let keyHex = getKeyHex(cryptoCode);
  22. let ivHex = getIvHex();
  23. try {
  24. key = JSON.stringify(key);
  25. } catch (e) {
  26. console.warn(e);
  27. }
  28. return AES.encrypt(key, keyHex, {
  29. mode: CryptoJS.mode.CBC,
  30. padding: ZeroPadding,
  31. iv: ivHex,
  32. }).toString();
  33. };
  34. /**
  35. * 加密后转base64
  36. * @param {String}} key
  37. * @param {String} cryptoCode
  38. */
  39. export const getEncryptToBase64 = (key, cryptoCode) => {
  40. let encryptStr = getEncrypt(key, cryptoCode);
  41. let wordArray = Utf8.parse(encryptStr);
  42. return Base64.stringify(wordArray);
  43. };
  44. /**
  45. * 解密
  46. * @param data
  47. * @returns {string}
  48. */
  49. export const getDecrypt = (data) => {
  50. let keyHex = getKeyHex();
  51. let ivHex = getIvHex();
  52. let decrypted = AES.decrypt(
  53. {
  54. ciphertext: Base64.parse(data),
  55. },
  56. keyHex,
  57. {
  58. mode: CryptoJS.mode.CBC,
  59. padding: ZeroPadding,
  60. iv: ivHex,
  61. }
  62. ).toString(Utf8);
  63. try {
  64. decrypted = JSON.parse(decrypted);
  65. } catch (e) {
  66. console.warn(e);
  67. }
  68. return decrypted;
  69. };
  70. /**
  71. * 对base64数据解密 先解析base64,在做解密
  72. * @param {String} data
  73. * @returns {string}
  74. */
  75. export const getDecryptByBase64 = (data) => {
  76. let parsedWordArray = Base64.parse(data);
  77. let decryptStr = parsedWordArray.toString(Utf8);
  78. return getDecrypt(decryptStr);
  79. };