import CryptoJS from 'crypto-js';

const key = CryptoJS.enc.Utf8.parse(import.meta.env.VITE_APP_KEY);
const iv = CryptoJS.enc.Utf8.parse(import.meta.env.VITE_APP_IV);

const crypto = {
  encrypt: (str) => {
    const encrypted = CryptoJS.AES.encrypt(str, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    // 将加密结果转换为字节数组，然后转换为十六进制字符串
    const hexString = CryptoJS.enc.Hex.stringify(encrypted.ciphertext);
    return hexString;
  },
  decrypt: (hexString) => {
    // 将十六进制字符串转换回字节数组
    const ciphertext = CryptoJS.enc.Hex.parse(hexString);
    const encryptedParams = CryptoJS.lib.CipherParams.create({ ciphertext });
    const decrypted = CryptoJS.AES.decrypt(encryptedParams, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
  }
};

export default crypto;
