1. 安装crypto-js
yarn add crypto-js
npm install crypto-js
2. 封装加密方法
const CryptoJS = require("crypto-js");
const SECRET_KEY = CryptoJS.enc.Utf8.parse("1234123412341234");
const SECRET_IV = CryptoJS.enc.Utf8.parse("1234123412341234");
export function encrypt(data) {
if (typeof data === "object") {
try {
data = JSON.stringify(data);
} catch (error) {
console.log("encrypt error:", error);
}
}
const ciphertext = CryptoJS.AES.encrypt(data, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}).toString();
return ciphertext;
}
export function decrypt(ciphertext) {
const result = CryptoJS.AES.decrypt({ciphertext:CryptoJS.enc.Base64.parse(ciphertext)}, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}).toString(CryptoJS.enc.Utf8);
return result;
}
3. 使用
<script>
import { encrypt, decrypt } from '@/utils/encryption'
export default {
methods: {
getData() {
let obj = {
name: '张三',
age: '66'
}
const data = encrypt(obj)
const decryptData = decrypt(data)
}
}
}
</script>