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 = "1234567890123456";
  const IV = "1234567890123456";

  var key = CryptoJS.enc.Utf8.parse(KEY);
  var iv = CryptoJS.enc.Utf8.parse(IV);
  var encrypted = CryptoJS.AES.encrypt(content, key, { iv: iv });
  return encrypted.toString();
};

/**
 * 获取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}`;
  }
};
