// 引入crypto-js包
import CryptoJS from 'crypto-js'




/**
 * AES加密
 * @param {any} word 加密数据
 */
export const cryptoEncrypt = (word) => {
  var key = CryptoJS.enc.Utf8.parse('填写密钥');
  var iv = CryptoJS.enc.Utf8.parse('填写偏移量');
  var encrypted = '';
  if (typeof(word) == 'string') {
      var srcs = CryptoJS.enc.Utf8.parse(word);
      encrypted = CryptoJS.AES.encrypt(srcs, key, {
          iv: iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
      });
  } else if (typeof(word) == 'object') {//对象格式的转成json字符串
      data = JSON.stringify(word);
      var srcs = CryptoJS.enc.Utf8.parse(data);
      encrypted = CryptoJS.AES.encrypt(srcs, key, {
          iv: iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
      })
  }
  return encrypted.ciphertext.toString();
}

/**
 * AES解密
 * @param {any} word 解密数据
 */
export const cryptoDecrypt = (word) => {
  var key = CryptoJS.enc.Utf8.parse('填写密钥');
  var iv = CryptoJS.enc.Utf8.parse('填写偏移量');
  var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  var decrypt = CryptoJS.AES.decrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
  });
  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐