0
0
NodejsHow-ToBeginner · 4 min read

How to Encrypt Data in Node.js Using Crypto Module

In Node.js, you can encrypt data using the built-in crypto module by creating a cipher with crypto.createCipheriv() and then updating it with your data. Use a secret key and initialization vector (IV) for security, and decrypt with crypto.createDecipheriv() using the same key and IV.
📐

Syntax

To encrypt data in Node.js, use the crypto.createCipheriv(algorithm, key, iv) method. Here:

  • algorithm: The encryption algorithm like 'aes-256-cbc'.
  • key: A secret key buffer matching the algorithm's key length.
  • iv: Initialization vector buffer for randomness.

Then call cipher.update(data) to encrypt data and cipher.final() to finish encryption.

javascript
const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 256-bit key
const iv = crypto.randomBytes(16);  // 128-bit IV

const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('your data here', 'utf8', 'hex');
encrypted += cipher.final('hex');

console.log(encrypted);
💻

Example

This example shows how to encrypt and then decrypt a text string using AES-256-CBC. It demonstrates generating a key and IV, encrypting the message, and then decrypting it back to the original text.

javascript
const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 256-bit key
const iv = crypto.randomBytes(16);  // 128-bit IV

const text = 'Hello, Node.js encryption!';

// Encrypt
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');

// Decrypt
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');

console.log('Encrypted:', encrypted);
console.log('Decrypted:', decrypted);
Output
Encrypted: <hexadecimal string> Decrypted: Hello, Node.js encryption!
⚠️

Common Pitfalls

Common mistakes when encrypting data in Node.js include:

  • Using a static or weak key instead of a securely generated random key.
  • Reusing the same initialization vector (IV) for multiple encryptions, which weakens security.
  • Not matching the encoding formats between update() and final() methods.
  • Forgetting to use createDecipheriv with the same key and IV for decryption.

Always keep your key and IV secret and never hardcode them in production code.

javascript
/* Wrong way: Reusing IV and static key (insecure) */
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = Buffer.from('12345678901234567890123456789012'); // static key (bad)
const iv = Buffer.from('1234567890123456'); // static IV (bad)

const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('data', 'utf8', 'hex');
encrypted += cipher.final('hex');

console.log('Encrypted:', encrypted);

/* Right way: Use random key and IV */
const key2 = crypto.randomBytes(32);
const iv2 = crypto.randomBytes(16);
const cipher2 = crypto.createCipheriv(algorithm, key2, iv2);
let encrypted2 = cipher2.update('data', 'utf8', 'hex');
encrypted2 += cipher2.final('hex');

console.log('Encrypted with secure key and IV:', encrypted2);
Output
Encrypted: 8d969eef6ecad3c29a3a629280e686cf Encrypted with secure key and IV: <hexadecimal string>
📊

Quick Reference

  • Algorithm: Use strong algorithms like 'aes-256-cbc'.
  • Key: Must be 32 bytes for AES-256.
  • IV: Must be 16 bytes and unique per encryption.
  • Encoding: Use 'utf8' for input and 'hex' or 'base64' for output.
  • Security: Never reuse IV or expose keys.

Key Takeaways

Use Node.js built-in crypto module with createCipheriv and createDecipheriv for encryption and decryption.
Always generate a secure random key and initialization vector (IV) for each encryption.
Match encoding formats between cipher update and final methods to avoid errors.
Never reuse the same IV for multiple encryptions to maintain security.
Keep keys and IVs secret and never hardcode them in production code.