import CryptoJS from 'crypto-js'


const KEY = 'wkwwkwwkwwkwwkwA'

/**
 * * 加密
 * @param data { string }
 * @returns { string } 加密后的数据
 */
export const cryptoEncode = (data) => {
  const key = CryptoJS.enc.Utf8.parse(KEY);
  const iv = CryptoJS.lib.WordArray.random(16); // 随机生成16字节的IV
  const encrypted = CryptoJS.AES.encrypt(data, key, {
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
    iv: iv,
  });
  // 将IV与加密后的数据拼接并以特定格式返回，以便在Java中分离IV和加密后的数据
  return iv.toString(CryptoJS.enc.Base64) + encrypted.toString();
};

export const cryptoDecode = (data) => {
  const key = CryptoJS.enc.Utf8.parse(KEY);
  const iv = CryptoJS.lib.WordArray.create(CryptoJS.enc.Utf8.parse(KEY).words.slice(0, 4)); // 前四个字节作为IV
  const bytes = CryptoJS.AES.decrypt(data, key, {
      iv: iv,
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
  });
  return bytes.toString(CryptoJS.enc.Utf8);
}
