前端js Aes对本地存储数据进行加密解密

1、npm install crypto-js

2、编写LocalStorage类

const CryptoJS = require('crypto-js');
class LocalStorage {
    constructor() {
        this.autoEncrypt = true
        this.aseKey = '12345678'
    }

    setItem(key, value) {
        var v = value
        if (this.autoEncrypt) {
            v = this.AesEncrypt(v)
        }
        localStorage.setItem(key, v)
    }

    getItem(key) {
        let v = localStorage.getItem(key)
        if (v) {
            if (this.autoEncrypt) {
                return this.AesDecode(v)
            } else {
                return v
            }
        } else {
            return ''
        }
    }

    /* 
        AES 加密
    */
    AesEncrypt(v) {
        return CryptoJS.AES.encrypt(v, CryptoJS.enc.Utf8.parse(this.aseKey), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        }).toString()
    }
    /* 
        AES 解密
    */
    AesDecode(v) {
        return CryptoJS.AES.decrypt(v, CryptoJS.enc.Utf8.parse(this.aseKey), {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        }).toString(CryptoJS.enc.Utf8)
    }


}
const myLocalStorage = new LocalStorage()
myLocalStorage.setItem('token', '123123')
console.log(myLocalStorage.getItem('token'))
export {
    LocalStorage,
    myLocalStorage as localStorage,
}

3、不喜勿喷,谢谢!

你可能感兴趣的:(es6,utils)