(代码示例)使用crypto-js实现AES加密解密

bash 复制代码
npm install crypto-js
# 官方文档 <https://www.npmjs.com/package/crypto-js>

适用于需要检验的场景

  • 比如敏感的前端query参数
  • Cookie中的某个字段
  • 数据库中的敏感字段
js 复制代码
// ====================做成文件====================
const CryptoJS = require("crypto-js");
// 秘钥  
const aesKey = "59abbe5e10adf20f883ec3949ba6e057";  
// 将秘钥转换成Utf8字节数组  
const key = CryptoJS.enc.Utf8.parse(aesKey);  
// 加密参数  
const option = {  
    iv: CryptoJS.enc.Utf8.parse(aesKey.substr(0, 16)),  
    mode: CryptoJS.mode.CBC,  
    padding: CryptoJS.pad.Pkcs7,  
}; 

/** data 是要 加密的数据 */
export function enCode(data) {
    const encrypt = CryptoJS.AES.encrypt(JSON.stringify(data), key, option);  
    return encrypt.toString();  // 加密之后的字符串 A。一旦A修改了,那么解密就会失败。
}
/** codeStr 是要 解密的字符串 A */
export function deCode(codeStr) {
    const decrypt = CryptoJS.AES.decrypt(codeStr, key, option);  
    return JSON.parse(decrypt.toString(CryptoJS.enc.Utf8)); //解密后的数据  
}

// ================================================
// 测试数据
const data = {  
    name: "张三",  
    sex: '男',  
    height: 180
}; 
相关推荐
chao-Cyril2 分钟前
从入门到进阶:前端开发的成长之路与实战感悟
前端·javascript·vue.js
shalou290118 分钟前
Spring 核心技术解析【纯干货版】- Ⅶ:Spring 切面编程模块 Spring-Instrument 模块精讲
前端·数据库·spring
大时光29 分钟前
js 封装 动画效果
前端
大时光32 分钟前
html翻页时钟 效果
前端
大猫子的技术日记37 分钟前
2025 AI Agent 开发实战指南:从上下文工程到多智能体协作
前端·人工智能·bootstrap
前端达人44 分钟前
被JavaScript忽视的Web Animations API:为什么说它是前端动画的真正未来?
开发语言·前端·javascript·ecmascript
忧郁的橙子.1 小时前
04-从零搭建本地AI对话系统:Ollama + DeepSeek-R1:7B + Streamlit
前端·chrome
PTC1 小时前
做了个 EPUB 阅读器,被「阅读进度同步」折磨了一周,总结 4 个血泪教训
前端
Aaron_Feng1 小时前
适配Swift 6 Sendable:用AALock优雅解决线程安全与不可变引用难题
前端
大时光2 小时前
gsap 配置解读 --7
前端