To securely encrypt and decrypt data in a Node.js application, you can use the crypto module with AES encryption.
Here’s a recommended approach using AES-256-CBC encryption, which is commonly used and considered strong.
const crypto = require('crypto');
const assert = require('assert');
const algorithm = 'aes-256-cbc';
// Generate a 32-byte (256-bit) key and a 16-byte IV (AES block size)
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return { iv: iv.toString('hex'), encryptedData: encrypted };
}
function decrypt(encryptedData, ivHex) {
const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(ivHex, 'hex'));
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Usage example
const text = 'I love kittens';
const encrypted = encrypt(text);
console.log("Encrypted:", encrypted);
const decrypted = decrypt(encrypted.encryptedData, encrypted.iv);
console.log("Decrypted:", decrypted);
// Check if decrypted text matches the original
assert.strictEqual(decrypted, text);
- The code specifies aes-256-cbc for AES encryption with a 256-bit key, a strong standard for secure encryption. This ensures data is encrypted with a secure algorithm.
- A 32-byte key and a 16-byte initialization vector (IV) are randomly generated, which are crucial for encryption security. The IV makes each encryption unique, even with the same key.
- createCipheriv is used to initialize encryption with the algorithm, key, and IV, then cipher.update and cipher.final convert the plaintext into encrypted hex data. This results in a securely encrypted message.
- The decryption process reverses encryption using createDecipheriv, taking the encrypted data and IV to restore the original text. This verifies that only with the right key and IV can data be decrypted back to its original form.
- An assert statement compares the decrypted text to the original, ensuring the encryption-decryption cycle is intact.