vue 开发AES256加密解密
时间: 2025-02-22 16:22:17 浏览: 64
### 在 Vue.js 中使用 AES-256 实现加密和解密
为了在 Vue.js 项目中实现 AES-256 加密和解密功能,可以采用 `crypto-js` 库。此库支持多种加密方式,并允许开发者轻松集成到前端应用中。
#### 安装依赖
首先,在项目根目录下通过命令行工具安装所需的开发依赖:
```bash
npm install crypto-js --save-dev
```
#### 创建 AES 工具类
接着,创建一个新的 JavaScript 文件(例如命名为 `AESUtil.js`),用于定义加密和解密逻辑:
```javascript
import CryptoJS from 'crypto-js';
// 设置固定的密钥与初始化向量
const SECRET_KEY = 'your-secret-key-here'; // 需要是一个32字节字符串以适应AES-256
const IV = 'initialization-vector'; // 可选参数,默认为空字符填充
/**
* 使用 AES-256-CBC 模式对明文进行加密处理.
*/
export function encryptByAES(text) {
try {
let encrypted = CryptoJS.AES.encrypt(
text,
CryptoJS.enc.Utf8.parse(SECRET_KEY),
{ iv: CryptoJS.enc.Utf8.parse(IV), mode: CryptoJS.mode.CBC }
);
return encrypted.toString();
} catch (e) {
console.error('Encryption failed:', e);
throw new Error('Failed to encrypt the data.');
}
}
/**
* 解析并返回经过 AES-256-CBC 加密后的密文对应的原始内容.
*/
export function decryptByAES(cipherText) {
if (!cipherText || cipherText === '') return '';
try {
let decrypted = CryptoJS.AES.decrypt(
cipherText,
CryptoJS.enc.Utf8.parse(SECRET_KEY),
{ iv: CryptoJS.enc.Utf8.parse(IV), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
);
return decrypted.toString(CryptoJS.enc.Utf8);
} catch (e) {
console.error('Decryption failed:', e);
throw new Error('Failed to decrypt the data.');
}
}
```
上述代码片段展示了如何利用 `crypto-js` 来完成基于 AES-256 的加解密操作[^4]。需要注意的是,这里假设采用了 CBC 模式的分组链接法来进行数据保护;同时设置了固定长度为 32 字符串形式的秘密密钥作为输入给定的 key 参数值[^5]。
#### 调用示例
最后可以在组件内部调用这些方法来测试其效果:
```html
<template>
<div id="app">
<!-- 输入框 -->
<input v-model="message" placeholder="Enter message..." />
<button @click="handleEncrypt">Encrypt</button>
<!-- 显示结果区域 -->
<p>Encrypted Text:</p>
<textarea readonly>{{ encryptedMessage }}</textarea>
<br />
<button @click="handleDecrypt">Decrypt</button>
<p>Decrypted Text:</p>
<textarea readonly>{{ decryptedMessage }}</textarea>
</div>
</template>
<script>
import { ref } from 'vue';
import { encryptByAES, decryptByAES } from './utils/AESUtil';
export default {
setup() {
const message = ref('');
const encryptedMessage = ref('');
const decryptedMessage = ref('');
function handleEncrypt() {
encryptedMessage.value = encryptByAES(message.value);
}
function handleDecrypt() {
decryptedMessage.value = decryptByAES(encryptedMessage.value);
}
return {
message,
encryptedMessage,
decryptedMessage,
handleEncrypt,
handleDecrypt,
};
},
};
</script>
```
这段模板描述了一个简单的界面,用户可以通过该界面对消息执行加密和解密动作,并查看相应的输出结果。
阅读全文
相关推荐




















