侧边栏壁纸
博主头像
龍啓博主等级

Vue development

  • 累计撰写 11 篇文章
  • 累计创建 8 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

vuex-persistedstate的储存加密

龍啓
2022-07-28 / 0 评论 / 0 点赞 / 70 阅读 / 330 字
广告 广告

安装依赖

$ npm install crypto-js secure-web-storage

  or

$ yarn add crypto-js secure-web-storage

存储加密工具类

# @/utils/secure-storage.js

import sha256 from 'crypto-js/sha256'
import aes from 'crypto-js/aes'
import enc from 'crypto-js/enc-utf8'
import SecureStorage from 'secure-web-storage'

const SECRET_KEY = 'beetledata'

const secureStorage = (storage) => new SecureStorage(storage, {
  hash: function hash(key) {
    key = sha256(key, SECRET_KEY)

    return key.toString()
  },
  encrypt: function encrypt(data) {
    data = aes.encrypt(data, SECRET_KEY)

    data = data.toString()

    return data
  },
  decrypt: function decrypt(data) {
    data = aes.decrypt(data, SECRET_KEY)

    data = data.toString(enc)

    return data
  }
})

export const secureLocalStorage = secureStorage(window.localStorage)
export const secureSessionStorage = secureStorage(window.sessionStorage)

在vuex中应用存储加密

# @/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import createPersistedState from 'vuex-persistedstate'
import { secureLocalStorage, secureSessionStorage } from '@/utils/secure-storage'

Vue.use(Vuex)

//正则 添加同一级modules的js
const modulesFiles = require.context('./modules', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

// 数据本地化
export const localStorageData = createPersistedState({
  key: 'vuex',
  paths: ['app'],
  storage: {
    getItem: key => secureLocalStorage.getItem(key),
    setItem: (key, value) => secureLocalStorage.setItem(key, value),
    removeItem: key => secureLocalStorage.removeItem(key)
  }
  // reducer: state => ({}) 存储指定数据
})
export const sessionStorageData = createPersistedState({
  key: 'vuex',
  paths: ['permission'],
  storage: {
    getItem: key => secureSessionStorage.getItem(key),
    setItem: (key, value) => secureSessionStorage.setItem(key, value),
    removeItem: key => secureSessionStorage.removeItem(key)
  }
  // reducer: state => ({})
})

const store = new Vuex.Store({
  modules,
  getters,
  plugins: [localStorageData, sessionStorageData]
})
export default store


0

评论区