加密及解密代码
首先下载需要的npm包,可执行以下命令下载
npm install crypto-js --save-dev
npm install js-md5 --save-dev
AesUtil.js
let CryptoJS = require("crypto-js")
let MD5 = require("crypto-js/md5")
const IV = '0102030405060708'
// 加密方法
export function Encrypt (data, key) {
key = CryptoJS.enc.Utf8.parse(MD5(key))
let iv = CryptoJS.enc.Utf8.parse(IV)
let encrypted = ''
if (typeof (data) === "string") {
encrypted = CryptoJS.AES.encrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
} else if (typeof (data) === "object") {
data = JSON.stringify(data)
encrypted = CryptoJS.AES.encrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
}
return encrypted.toString()
}
// 解密方法
export function Decrypt (data, key) {
key = CryptoJS.enc.Utf8.parse(MD5(key))
let iv = CryptoJS.enc.Utf8.parse(IV)
let decrypted = CryptoJS.AES.encrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
let decryptedStr = decrypted.toString(CryptoJS.enc.Utf8)
return decryptedStr.toString()
}
具体调用如下:
import { Encrypt, Decrypt } from 'xxx/AesUtil.js'(xxx代表文件路径)
let obj = {
"name": 'aa',
"age": 12
}
let enstr = Encrypt(obj, 'info')
console.log(enstr)
let destr = Decrypt(enstr, 'info')
conosle.log(destr )