使用场景:可以加密localStorage,这样数据就不会裸奔了
npm install crypto-js
import CryptoJS from "crypto-js";
const CryptoJS = require("crypto-js");
设置密钥和密钥偏移量
const SECRET_KEY = CryptoJS.enc.Utf8.parse("3333e6e143439161");
const SECRET_IV = CryptoJS.enc.Utf8.parse("e3bbe7e3ba84431a");
加密方法封装
export function encrypt(data) {
if (typeof data === "object") {
try {
data = JSON.stringify(data);
} catch (error) {
console.log("encrypt error:", error);
}
}
const dataHex = CryptoJS.enc.Utf8.parse(data);
const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.ciphertext.toString();
}
解密方法封装
export function decrypt(data) {
const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
使用方法
import { encrypt, decrypt } from '@/utils/encrypt';
实战
import { encrypt, decrypt } from './CryptoJS';
class FnStorage {
set(key: string, obj) {
localStorage.setItem(key, encrypt(JSON.stringify(obj)));
}
get(key: string) {
if (localStorage.getItem(key) === null) {
return '';
}
return JSON.parse(decrypt(localStorage.getItem(key)));
}
remove(key: string) {
localStorage.removeItem(key);
}
clear() {
localStorage.clear();
}
};
export default FnStorage;