共计 1149 个字符,预计需要花费 3 分钟才能阅读完成。
背景
公司后端加解密应用的是 aes
的形式,过后找了好多前端加解密的库,最初决定应用 crypto-js
封装了加解密办法。
筹备工作
在前端我的项目中装置 crypto-js
包
npm install crypto-js
具体应用
import CryptoJS from 'crypto-js' | |
const crpytoConfig = { | |
AES_KEY: 'key', | |
AES_IV: 'iv', | |
} | |
/** | |
* @description aes 加密 | |
* @param {string} word 须要加密的字符串 | |
*/ | |
const cryptoEncrypt = word => {const { AES_IV, AES_KEY} = crpytoConfig | |
const key = CryptoJS.enc.Utf8.parse(AES_KEY) | |
const iv = CryptoJS.enc.Utf8.parse(AES_IV) | |
const srcs = CryptoJS.enc.Utf8.parse(word) | |
let encrypted = ''; | |
encrypted = CryptoJS.AES.encrypt(srcs, key, { | |
iv, | |
mode: CryptoJS.mode.CBC, | |
padding: CryptoJS.pad.Pkcs7 | |
}) | |
return encrypted.ciphertext.toString(CryptoJS.enc.Base64) | |
} | |
/** | |
* @description aes 解密 | |
* @param {string} word 须要解密的字符串 | |
*/ | |
const cryptoDecrypt = word => {const { AES_IV, AES_KEY} = crpytoConfig | |
// 因为和咱们公司后端加密得出的数据有些出入 所以这里做了字符替换能力失常进行加解密 所以下边这句视状况而定到底加不加 | |
const strWord = word.replace(/\_/g, '/').replace(/\-/g, '+') | |
const key = CryptoJS.enc.Utf8.parse(AES_KEY) | |
const iv = CryptoJS.enc.Utf8.parse(AES_IV) | |
const encryptedHexStr = CryptoJS.enc.Base64.parse(strWord) | |
const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr) | |
let decrypt = '' | |
decrypt = CryptoJS.AES.decrypt(srcs, key, { | |
iv, | |
mode: CryptoJS.mode.CBC, | |
padding: CryptoJS.pad.Pkcs7 | |
}) | |
return decrypt.toString(CryptoJS.enc.Utf8).toString()} |
正文完
发表至: javascript
2022-01-14