美文网首页
CryptoJS加密

CryptoJS加密

作者: 温水煮青蛙a | 来源:发表于2023-02-16 14:00 被阅读0次
    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);
    }
    
    

    相关文章

      网友评论

          本文标题:CryptoJS加密

          本文链接:https://www.haomeiwen.com/subject/djypkdtx.html