安装依赖
$ 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