1. 安装crypto-js库:
| npm install crypto-js |
| |
| yarn add crypto-js |
2. 封装encryption.js
| |
| import CryptoJS from 'crypto-js'; |
| |
| |
| export function encrypt(text, key) { |
| return CryptoJS.AES.encrypt(text, key).toString(); |
| } |
| |
| |
| export function decrypt(ciphertext, key) { |
| const bytes = CryptoJS.AES.decrypt(ciphertext, key); |
| return bytes.toString(CryptoJS.enc.Utf8); |
| } |
3. 使用
| <template> |
| <div> |
| <h1>AES Encryption Example</h1> |
| <input v-model="inputText" placeholder="Enter text to encrypt" /> |
| <input v-model="encryptionKey" placeholder="Enter encryption key" /> |
| <button @click="handleEncrypt">Encrypt</button> |
| <button @click="handleDecrypt">Decrypt</button> |
| <p>Encrypted Text: {{ encryptedText }}</p> |
| <p>Decrypted Text: {{ decryptedText }}</p> |
| </div> |
| </template> |
| |
| <script> |
| // 导入封装好的加解密方法 |
| import { encrypt, decrypt } from '@/utils/encryption'; |
| |
| export default { |
| data() { |
| return { |
| inputText: '', |
| encryptionKey: '', |
| encryptedText: '', |
| decryptedText: '' |
| }; |
| }, |
| methods: { |
| handleEncrypt() { |
| this.encryptedText = encrypt(this.inputText, this.encryptionKey); |
| }, |
| handleDecrypt() { |
| this.decryptedText = decrypt(this.encryptedText, this.encryptionKey); |
| } |
| } |
| }; |
| </script> |
| |
| <style scoped> |
| /* 添加一些简单的样式 */ |
| input { |
| margin-bottom: 10px; |
| display: block; |
| } |
| button { |
| margin-right: 10px; |
| } |
| </style> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程