在Ubuntu系统中使用Node.js实现数据加密与解密,你可以使用内置的crypto模块。以下是一个简单的示例,展示了如何使用crypto模块进行AES-256-CBC加密和解密。
首先,确保你已经安装了Node.js。如果没有,请访问Node.js官网下载并安装。
创建一个新的JavaScript文件,例如encryptDecrypt.js。
在encryptDecrypt.js文件中,编写以下代码:
const crypto = require('crypto');
// 加密函数
function encrypt(text, key) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return {
iv: iv.toString('hex'),
content: encrypted.toString('hex')
};
}
// 解密函数
function decrypt(hash, key) {
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), Buffer.from(hash.iv, 'hex'));
const decrpyted = Buffer.concat([decipher.update(Buffer.from(hash.content, 'hex')), decipher.final()]);
return decrpyted.toString();
}
// 示例
const key = crypto.randomBytes(32); // 生成一个32字节的密钥
const text = 'Hello, World!';
const encrypted = encrypt(text, key);
const decrypted = decrypt(encrypted, key);
console.log('原始文本:', text);
console.log('加密后的文本:', encrypted);
console.log('解密后的文本:', decrypted);
encryptDecrypt.js文件:node encryptDecrypt.js
你将看到原始文本、加密后的文本和解密后的文本。
请注意,这个示例使用了AES-256-CBC加密算法,你可以根据需要选择其他算法。同时,确保妥善保管好密钥,因为它是加密和解密的关键。