nodejs实现aes加密
时间: 2023-10-24 16:29:50 浏览: 118
你可以使用 `crypto` 模块来在 Node.js 中实现 AES 加密。下面是一个简单的示例代码,演示了如何使用 AES-128-CBC 模式进行加密和解密:
```javascript
const crypto = require('crypto');
function encrypt(text, key, iv) {
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
function decrypt(encryptedText, key, iv) {
const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// 使用示例
const plaintext = 'Hello, AES!';
const key = '0123456789abcdef';
const iv = 'abcdef0123456789';
const encryptedText = encrypt(plaintext, key, iv);
console.log('Encrypted:', encryptedText);
const decryptedText = decrypt(encryptedText, key, iv);
console.log('Decrypted:', decryptedText);
```
请注意,上述示例中使用的是 AES-128,密钥和初始化向量 (IV) 都是 16 字节的十六进制字符串。你可以根据需要更改密钥和 IV 的值,并根据你的加密需求选择适当的 AES 模式和密钥大小。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)