39 lines
1.3 KiB
JavaScript
39 lines
1.3 KiB
JavaScript
|
import * as CryptoJS from 'crypto-js/crypto-js';
|
|||
|
// 工具类
|
|||
|
const CryptoUtil = require('crypto-js')
|
|||
|
// 约定密钥(与后端密钥保持一致)
|
|||
|
const key = CryptoUtil.enc.Utf8.parse('C0Bb0RsnNZYf8XQtcgdfcpuHw2JBTV9A') // 密钥16位长度字符 内容可自定义
|
|||
|
const IV = CryptoUtil.enc.Utf8.parse('fc6cb288893f45be') // 密钥偏移量 16位长度字符
|
|||
|
|
|||
|
/**
|
|||
|
* AES对称加密 (CBC模式,需要偏移量)
|
|||
|
* @param {Object} params 明文参数
|
|||
|
*/
|
|||
|
export function encrypt(params) {
|
|||
|
// 明文参数
|
|||
|
const str = CryptoUtil.enc.Utf8.parse(params)
|
|||
|
// 加密
|
|||
|
const encryptedData = CryptoUtil.AES.encrypt(str, key, {
|
|||
|
iv: IV,
|
|||
|
mode: CryptoUtil.mode.CBC, // AES加密模式
|
|||
|
padding: CryptoUtil.pad.Pkcs7 // 填充方式
|
|||
|
})
|
|||
|
return CryptoUtil.enc.Base64.stringify(encryptedData.ciphertext) // 返回base64格式密文
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* AES对称解密
|
|||
|
* @param {Object} params 加密参数
|
|||
|
*/
|
|||
|
export function decrypt(params) {
|
|||
|
// base64格式密文转换
|
|||
|
const base64 = CryptoUtil.enc.Base64.parse(params)
|
|||
|
const str = CryptoUtil.enc.Base64.stringify(base64)
|
|||
|
// 解密
|
|||
|
const decryptedData = CryptoUtil.AES.decrypt(str, key, {
|
|||
|
iv: IV,
|
|||
|
mode: CryptoUtil.mode.CBC, // AES加密模式
|
|||
|
padding: CryptoUtil.pad.Pkcs7 // 填充方式
|
|||
|
})
|
|||
|
return CryptoUtil.enc.Utf8.stringify(decryptedData).toString() // 返回明文
|
|||
|
}
|