Node.js Course
Node.js
/
Intermediate

Crypto Module

Definition

A core module that provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

Explain Like I'm New

The security vault of Node.js. It gives you the tools to securely hash passwords so hackers can't read them, generate random secure tokens for resetting passwords, and encrypt sensitive data like credit card numbers.

Real World Example

Creating a unique, un-guessable ID for a user's session token using `crypto.randomUUID()`.

Common Use Cases

  • •Password hashing (though bcrypt is preferred)
  • •Generating secure random strings
  • •Data encryption/decryption

Terminal Output

bash / terminal
const crypto = require('crypto'); // 1. Generate a secure Random UUID const newUserId = crypto.randomUUID(); console.log("UUID:", newUserId); // 2. Generate cryptographically secure random bytes (Great for API keys) const apiKey = crypto.randomBytes(32).toString('hex'); console.log("API Key:", apiKey); // 3. Hashing Data (One-way scramble) // We hash a string using the SHA-256 algorithm const secretMessage = "My Super Secret Password"; const hash = crypto.createHash('sha256').update(secretMessage).digest('hex'); console.log("Original:", secretMessage); console.log("SHA-256 Hash:", hash); // If even ONE letter changes, the hash changes completely. const hash2 = crypto.createHash('sha256').update("My Super Secret Password!").digest('hex'); console.log("Changed Hash:", hash2);

Interview Questions

basic

  • How do you generate a standard UUID (v4) string using the crypto module?

intermediate

  • What is a Hash? Can a Hash be reversed back to the original text?

advanced

  • What is the difference between encryption and hashing?

Flash Cards

Question

How do you generate a UUID?

Click to reveal answer
Answer

Using the built-in method: `crypto.randomUUID()`.

Question

What is the difference between encryption and hashing?

Click to reveal answer
Answer

Encryption is two-way: You lock the data with a key, and later you (or someone else) uses the key to unlock and read it. Hashing is one-way: You scramble a password into a fingerprint. It is mathematically impossible to reverse the fingerprint back into the password. You verify logins by hashing the entered password and comparing the fingerprints.