import CryptoJS from 'crypto-js'

/**
 * AES对称加密与解密方法
 */
const random = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
// 获取key，
export function generateKey(length = 16) {
  let str = ''
  for (let i = 0; i < length; i++) {
    str = str + random.charAt(Math.random() * random.length)
  }
  return str
}

// 加密
export function encryptedData(plain, key) {
  const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plain), CryptoJS.enc.Utf8.parse(key), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

// 解密
export function decryptedData(cipher, key) {
  const decrypt = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(key), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}
