先上效果
1. 安装
// 开发依赖
"crypto-js": "^4.1.1",
npm install crypto-js
2. 核心代码
/*
* @Author: Null
* @Date: 2022-08-16 11:39:58
* @Description: crypto-js 加密库
*/
import CryptoJS from 'crypto-js'
const secretKey = '1234567890000000' //16位
const key = CryptoJS.enc.Utf8.parse(secretKey)
const iv = CryptoJS.enc.Utf8.parse(secretKey)
//aes加密
export function encrypt(word) {
let encrypted = ''
if (typeof word == 'string') {
const srcs = CryptoJS.enc.Utf8.parse(word)
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
} else if (typeof word == 'object') {
//对象格式的转成json字符串
const data = JSON.stringify(word)
const srcs = CryptoJS.enc.Utf8.parse(data)
encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
}
return encrypted.ciphertext.toString()
}
// aes解密
export function decrypt(word) {
const encryptedHexStr = CryptoJS.enc.Hex.parse(word)
const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr)
const decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
return decryptedStr.toString()
}
3. 加密/解密方法
import { encrypt, decrypt } from '@/utils/cryptoJs/index'
// CryptoJS加密测试
encryptionFun () {
this.encryptionLoading = true
setTimeout(() => {
const secretText = encrypt(this.encryptionText)
console.log('CryptoJS加密测试', secretText)
this.encryptionTextStr = secretText
this.encryptionLoading = false
}, 500)
},
// CryptoJS解密测试
decryptFun () {
this.decryptLoading = true
setTimeout(() => {
const plainText = decrypt(this.decryptText)
console.log('CryptoJS解密测试', plainText)
this.decryptTextStr = plainText
this.decryptLoading = false
}, 500)
},
完结散花...