Crypto Module

Crypto Module

Security is paramount in backend development. The Crypto module provides cryptographic functionality, including a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

You will use the Crypto module to hash user passwords before saving them to a database, encrypt sensitive data, and generate secure random tokens.


1. Hashing Data

A hash function takes an input (like a password) and returns a fixed-size string of bytes. It is a one-way street: you cannot easily reverse a hash back to its original string.

Creating a SHA-256 Hash

const crypto = require('crypto');

const secretMessage = "mySuperSecretPassword123";

// Create a hash using the SHA-256 algorithm const hash = crypto.createHash('sha256') .update(secretMessage) .digest('hex');

console.log('Original Message:', secretMessage); console.log('Hashed Result:', hash);

If even a single character in the original message changes, the output hash will be completely different.


2. Generating Random Tokens

When creating password reset links or session IDs, you need secure random strings that cannot be guessed by attackers. The crypto.randomBytes() method is perfect for this.

Secure Random Data

const crypto = require('crypto');

// Generate 16 bytes of random data and convert to hex string const secureToken = crypto.randomBytes(16).toString('hex');

console.log('Random Token:', secureToken); // Output example: "b3f8a9e6d7c2f10..."


Exercise

?

What is a key characteristic of a cryptographic hash function?