Basic Cryptography in Node.js using the `crypto` Module

Learn fundamental cryptographic operations in Node.js using the built-in `crypto` module. This tutorial covers hashing, HMAC, AES encryption and decryption, and demonstrates their usage with code examples, providing a foundation for building secure Node.js applications.



Basic Cryptography in Node.js

Node.js provides the built-in `crypto` module for performing various cryptographic operations. It offers methods for hashing, HMAC (Hash-based Message Authentication Code), encryption, decryption, signing, and verification. This guide provides a basic overview of these functions.

Understanding Hashing and HMAC

  • Hashing: A one-way function that transforms arbitrary input data into a fixed-size string of bits (the hash). The same input always produces the same hash; however, it's computationally infeasible to determine the original input from the hash.
  • HMAC (Hash-based Message Authentication Code): A hash algorithm that includes a secret key. It's used to verify data integrity and authenticity. A change in the data or the key will change the resulting HMAC.

Example 1: Using HMAC

This example demonstrates calculating an HMAC using the SHA256 algorithm:


const crypto = require('crypto');
const secret = 'abcdefg';
const hmac = crypto.createHmac('sha256', secret)
  .update('My message')
  .digest('hex');
console.log(hmac);

Example 2: Encryption with Cipher

This example uses the AES (Advanced Encryption Standard) algorithm to encrypt data:


const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'password');
let encrypted = cipher.update('mytext', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);

Example 3: Decryption with Decipher

This example decrypts data encrypted using AES:


const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'password');
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);