encryption.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import CryptoJS from 'crypto-js'
  2. import CryptoJSCore from 'crypto-js/core'
  3. import AES from 'crypto-js/aes'
  4. import ZeroPadding from 'crypto-js/pad-zeropadding'
  5. import Utf8, { parse } from 'crypto-js/enc-utf8'
  6. import Base64 from 'crypto-js/enc-base64'
  7. /*
  8. * 加密 解密
  9. */
  10. const keyHex = parse('1111111111111111') // 十六位数作为密钥,自行修改
  11. const ivHex = CryptoJS.lib.WordArray.random(128 / 8) // 十六位数作为密钥偏移量 随机生成
  12. /**
  13. * 加密
  14. * @param {String} key
  15. * @returns {string}
  16. */
  17. // 加密后的结果通常是一个CipherParams对象,其中包含了加密后的密文数据,而密文数据本身是一个WordArray对象。同样,在解密过程中,解密后的结果也是一个WordArray对象。
  18. export const getEncrypt = (key) => {
  19. try {
  20. key = JSON.stringify(key)
  21. } catch (e) {
  22. console.warn(e)
  23. }
  24. // key需要是WordArray类型
  25. return JSON.stringify({
  26. encrypt: AES.encrypt(key, keyHex, {
  27. mode: CryptoJSCore.mode.CBC,
  28. padding: ZeroPadding,
  29. iv: ivHex,
  30. }).toString(),
  31. iv: ivHex,
  32. })
  33. }
  34. /**
  35. * 加密后转base64
  36. * @param {String}} key
  37. */
  38. export const getEncryptToBase64 = (key) => {
  39. const encryptStr = getEncrypt(key)
  40. const wordArray = Utf8.parse(encryptStr) //转为WordArray对象
  41. return Base64.stringify(wordArray)
  42. }
  43. /**
  44. * 解密
  45. * @param data
  46. * @returns {string}
  47. */
  48. export const getDecrypt = (data) => {
  49. let { encrypt, iv } = JSON.parse(data)
  50. let decrypted = AES.decrypt(
  51. {
  52. ciphertext: Base64.parse(encrypt),
  53. },
  54. keyHex,
  55. {
  56. mode: CryptoJSCore.mode.CBC,
  57. padding: ZeroPadding,
  58. iv: iv,
  59. }
  60. ).toString(Utf8) //转换为指定编码的字符串
  61. try {
  62. decrypted = JSON.parse(decrypted)
  63. } catch (e) {
  64. console.warn(e)
  65. }
  66. return decrypted
  67. }
  68. /**
  69. * 对base64数据解密 先解析base64,在做解密
  70. * @param {String} data
  71. * @returns {string}
  72. */
  73. export const getDecryptByBase64 = (data) => {
  74. // 将Base64字符串转换为WordArray
  75. const parsedWordArray = Base64.parse(data)
  76. // WordArray对象转换成一个UTF-8编码的字符串
  77. const decryptStr = Utf8.stringify(parsedWordArray)
  78. return getDecrypt(decryptStr)
  79. }