在Ubuntu系统中,可以使用Node.js的内置crypto
模块来进行加密和解密操作。以下是一个简单的示例,展示了如何使用crypto
模块进行AES加密和解密。
首先,确保已经安装了Node.js。如果没有,请访问Node.js官网下载并安装。
然后,创建一个名为encryptDecrypt.js
的文件,并将以下代码粘贴到文件中:
const crypto = require('crypto');
// 加密函数
function encrypt(text, key) {
const cipher = crypto.createCipher('aes-256-cbc', key);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return {
iv: cipher.iv,
content: encrypted.toString('hex')
};
}
// 解密函数
function decrypt(hash, key) {
const decipher = crypto.createDecipheriv('aes-256-cbc', key, hash.iv);
const decrpyted = Buffer.concat([decipher.update(Buffer.from(hash.content, 'hex')), decipher.final()]);
return decrpyted.toString();
}
// 示例
const text = 'Hello, World!';
const key = crypto.randomBytes(32); // 生成一个32字节的密钥
const encrypted = encrypt(text, key);
console.log('Encrypted:', encrypted);
const decrypted = decrypt(encrypted, key);
console.log('Decrypted:', decrypted);
保存文件后,在终端中运行以下命令:
node encryptDecrypt.js
这将输出加密后的文本和解密后的原始文本。
请注意,这个示例使用了AES-256-CBC加密算法,你可以根据需要更改为其他算法。同时,密钥(key)应该是随机生成的,并且在实际应用中需要妥善保管,因为它是加密和解密的关键。在这个示例中,我们为了简便,每次运行都会生成一个新的随机密钥。