CryptoJS加密

2023-02-16  本文已影响0人  温水煮青蛙a
import Cookies from 'js-cookie';
import CryptoJS from 'crypto-js';

const idToken = 'id_token';
const refreshToken = 'refresh_token';

// key
const secretKey = "c1b34ea814586db4a22dad37e11c7256322ab0eee3a14ed1898f93d7a264242f";
const secretIv = "c1b34ea814586db4a22dad37e11c7256"


/**
 * 加密
 */
export function encrypted(params) {
  const key = CryptoJS.enc.Base64.parse(secretKey)
  const iv = CryptoJS.enc.Utf8.parse(secretIv)
  let result = CryptoJS.AES.encrypt(params, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return result.toString();
}

/**
 * 解密
export function decrypted(params) {
  const key = CryptoJS.enc.Base64.parse(secretKey);
  const iv = CryptoJS.enc.Utf8.parse(secretIv)
  const decrypt = CryptoJS.AES.decrypt(params, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });

  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

export function getToken() {
  let id = Cookies.get(idToken);
  let refresh = Cookies.get(refreshToken);
  if (id && refresh) {
    id = decrypted(id);
    refresh = decrypted(refresh);
    return {
      'id_token': id,
      'refresh_token': refresh
    }
  } else {
    return {
      'id_token': '',
      'refresh_token': ''
    }
  }
}

export function setTokenAction(token) {
  let { id_token = '', refresh_token = '' } = token;
  id_token = encrypted(id_token)
  refresh_token = encrypted(refresh_token)
  Cookies.set(idToken, id_token, { expires: 1 });
  Cookies.set(refreshToken, refresh_token, { expires: 1 });
}

export function removeTokenAction() {
  Cookies.remove(idToken);
  Cookies.remove(refreshToken);
}

上一篇下一篇

猜你喜欢

热点阅读