前言
应项目需要需要使用AES进行数据的加密解密。
使用步骤
一、安装依赖
npm install crypto-js -S
二、在js工具文件夹内创建aes.js文件
import CryptoJS from 'crypto-js'
/**
* @author wangtongxue
* @date 2020/12/14 12:18 下午
* @description 使用AES加密解密
* @returns CryptoFiles的实例化对象
**/
class CryptoFiles {
constructor () {
this.key = CryptoJS.enc.Utf8.parse('***') // 密钥
this.options = {
iv: this.key,
mode: CryptoJS.mode.CBC, // CBC | ECB
padding: CryptoJS.pad.ZeroPadding
}
}
// 加密 word需要加密的字符串
encrypt (word) {
let words = CryptoJS.enc.Utf8.parse(word)
let encrypted = CryptoJS.AES.encrypt(words, this.key, this.options)
return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
}
// 解密 word需要解密的字符串
decrypt (word) {
let base64 = CryptoJS.enc.Base64.parse(word)
let src = CryptoJS.enc.Base64.stringify(base64)
let decrypt = CryptoJS.AES.decrypt(src, this.key, this.options)
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8)
return decryptedStr.toString()
}
}
let cryptoFiles = null
export default function () {
return cryptoFiles || (cryptoFiles = new CryptoFiles())
}
使用
import aes from '@/utils/aes'
const cryptoFiles = aes()
const word = 'example'
cryptoFiles.encrypt(word)
cryptoFiles.decrypt(word)
备注:记录当前加密的方式,供后续查阅使用