import CryptoJS from 'crypto-js';
import { isValid, decode } from 'js-base64';

/**
 * AES 加密并转为 base64
 * @param plaintext 数据字符串
 * @param aeskey 密钥
 * @returns 加密字符串
 */
export function encryptAES(plaintext: string, aeskey: string): string {
  const nowRoaund = new Date().getTime().toString(6);
  const key = CryptoJS.enc.Utf8.parse(aeskey);
  const iv = CryptoJS.enc.Utf8.parse(nowRoaund);
  const encrypted = CryptoJS.AES.encrypt(`${nowRoaund}${plaintext}`, key, {
    iv: iv,
    blockSize: 16,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
    format: CryptoJS.format.OpenSSL,
  });
  return encrypted.toString();
}

/**
 * AES 解密
 * @param ciphertext 加密字符串
 * @param aeskey 密钥
 * @returns 数据字符串
 */
export function decryptAES(ciphertext: string, aeskey: string): string {
  const nowRoaund = new Date().getTime().toString(6);
  const key = CryptoJS.enc.Utf8.parse(aeskey);
  const iv = CryptoJS.enc.Utf8.parse(nowRoaund);
  const decrypted = CryptoJS.AES.decrypt(ciphertext, key, {
    iv: iv,
    blockSize: 16,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
    format: CryptoJS.format.OpenSSL,
  });
  const base64Str = decrypted.toString(CryptoJS.enc.Base64);
  if (isValid(base64Str)) {
    const str = decode(base64Str);
    const idx = str.indexOf(':)', 10);
    if (idx > 10) {
      return str.substring(idx + 2);
    }
  }
  return '';
}
