在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加密算法,你可以根據需要選擇其他算法。同時,確保妥善保管好密鑰,因為它是加密和解密的關鍵。