在Ubuntu上使用JavaScript進行數據加密,你可以選擇多種庫和方法。以下是一些流行的方法和庫:
crypto
模塊:
Node.js內置了一個名為crypto
的模塊,它提供了各種加密算法,如AES、RSA等。以下是一個使用AES-256-CBC算法進行加密和解密的例子:const crypto = require('crypto');
// 加密函數
function encrypt(text, secretKey) {
const cipher = crypto.createCipheriv('aes-256-cbc', secretKey, Buffer.alloc(16, '0'));
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// 解密函數
function decrypt(encryptedText, secretKey) {
const decipher = crypto.createDecipheriv('aes-256-cbc', secretKey, Buffer.alloc(16, '0'));
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
const secretKey = crypto.randomBytes(32); // 生成一個32字節的密鑰
const text = 'Hello, World!';
const encryptedText = encrypt(text, secretKey);
console.log('Encrypted:', encryptedText);
const decryptedText = decrypt(encryptedText, secretKey);
console.log('Decrypted:', decryptedText);
async function encrypt(text, password) {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const salt = crypto.getRandomValues(new Uint8Array(16));
const keyMaterial = await window.crypto.subtle.importKey(
'raw',
encoder.encode(password),
{ name: 'AES-GCM' },
false,
['encrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encryptedData = await window.crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
keyMaterial,
data
);
return {
encryptedData: Array.from(new Uint8Array(encryptedData)),
salt: Array.from(salt),
iv: Array.from(iv)
};
}
async function decrypt(encryptedData, salt, iv, password) {
const encoder = new TextEncoder();
const keyMaterial = await window.crypto.subtle.importKey(
'raw',
encoder.encode(password),
{ name: 'AES-GCM' },
false,
['decrypt']
);
const decryptedData = await window.crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
keyMaterial,
new Uint8Array(encryptedData)
);
return new TextDecoder().decode(decryptedData);
}
const password = 'my-password';
const text = 'Hello, World!';
encrypt(text, password).then(({ encryptedData, salt, iv }) => {
console.log('Encrypted:', encryptedData);
console.log('Salt:', salt);
console.log('IV:', iv);
decrypt(encryptedData, salt, iv, password).then(decryptedText => {
console.log('Decrypted:', decryptedText);
});
});
請注意,這些代碼示例僅用于演示目的,實際應用中需要考慮更多的安全措施,比如密鑰管理和存儲、錯誤處理、算法選擇等。在生產環境中,確保遵循最佳安全實踐。