nodejs aes-128-ccm
时间: 2023-07-21 14:04:03 浏览: 265
以下是使用Node.js实现AES-128-CCM加密的示例代码:
```javascript
const crypto = require('crypto');
function encrypt(plainText, key, nonce) {
const cipher = crypto.createCipheriv('aes-128-ccm', key, nonce, {
authTagLength: 16
});
const encrypted = Buffer.concat([cipher.update(plainText, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return {
encrypted: encrypted.toString('base64'),
tag: tag.toString('base64')
};
}
function decrypt(encryptedText, key, nonce, tag) {
const decipher = crypto.createDecipheriv('aes-128-ccm', key, nonce, {
authTagLength: 16
});
decipher.setAuthTag(Buffer.from(tag, 'base64'));
const decrypted = Buffer.concat([decipher.update(Buffer.from(encryptedText, 'base64')), decipher.final()]);
return decrypted.toString('utf8');
}
// 示例使用
const plainText = 'Hello, World!';
const key = crypto.randomBytes(16); // 128-bit key
const nonce = crypto.randomBytes(12); // 96-bit nonce
const encryptedData = encrypt(plainText, key, nonce);
console.log('加密后的数据:', encryptedData);
const decryptedText = decrypt(encryptedData.encrypted, key, nonce, encryptedData.tag);
console.log('解密后的数据:', decryptedText);
```
请注意,这只是一个简单的示例,实际使用时需要根据具体需求进行适当的调整和处理。
阅读全文