const CryptoJS = require("crypto-js");

export const Base64 = (content) => {
  const words = CryptoJS.enc.Utf8.parse(content);
  const base64Str = CryptoJS.enc.Base64.stringify(words);

  return base64Str;
};

export const AES = (content) => {
  const KEY = "Qmth87863577qmth";
  // const IV = "1234567890123456";

  const key = CryptoJS.enc.Utf8.parse(KEY);
  // const iv = CryptoJS.enc.Utf8.parse(IV);
  const encrypted = CryptoJS.AES.encrypt(content, key, {
    // iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
};

export const AESDecode = (content) => {
  const KEY = "Qmth87863577qmth";
  // const IV = "1234567890123456";

  const key = CryptoJS.enc.Utf8.parse(KEY);

  // const iv = CryptoJS.enc.Utf8.parse(IV);
  const decrypted = CryptoJS.AES.decrypt(content, key, {
    // iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
};

/**
 * 获取authorisation
 * @param {Object} infos 相关信息
 * @param {String} type 类别：secret、token两种
 */
export const getAuthorization = (infos, type) => {
  // {type} {invoker}:base64(sha1(method&uri&timestamp&{secret}))
  if (type === "secret") {
    // accessKey | method&uri&timestamp&accessSecret
    const str = `${infos.method.toLowerCase()}&${infos.uri}&${
      infos.timestamp
    }&${infos.accessSecret}`;
    const sign = CryptoJS.enc.Base64.stringify(CryptoJS.SHA1(str));
    return `Secret ${infos.accessKey}:${sign}`;
  } else if (type === "token") {
    // userId | method&uri&timestamp&token
    const str = `${infos.method.toLowerCase()}&${infos.uri}&${
      infos.timestamp
    }&${infos.token}`;
    const sign = CryptoJS.enc.Base64.stringify(CryptoJS.SHA1(str));
    return `Token ${infos.account}:${sign}`;
  }
};
