crypto module
- Node.js course
- Intermediate
- Lesson 100/116
- 5 min
Learn the crypto module and hash functions.
The crypto module
Node.js's built-in crypto module does cryptographic operations: hashing, random byte generation, encryption and decryption. You do not need a separate package; the safest way to import is with the node: prefix: require("node:crypto").
Core concepts: a hash summarizes data into a fixed length; it is one-way and irreversible. HMAC adds a key to a hash; only the key holder can verify. AES is two-way symmetric encryption; it encrypts and decrypts data with a key. randomBytes generates cryptographically secure random bytes; unlike Math.random it is unpredictable. This module underlies password storage, JWT signing and the HTTPS handshake.
Hash properties
A hash function turns data into a fixed-length string. The same input always gives the same output (deterministic). You cannot recover the input from the output (one-way).
Example: crypto.createHash("sha256").update("hello").digest("hex") always gives a 64-character hex string. sha256 is one of the most common algorithms; md5 and sha1 are weak and not used for security. update() feeds data, digest("hex") returns the hash as a string. Hashes are used for password storage (with salt), file integrity checks, and detecting data changes. If two files have the same hash, their content is the same (most likely).
Practice Import the crypto module and test it
Import with const crypto = require("node:crypto");. Print "Crypto ready" with console.log.
Starter code
// Import the crypto module
// write here
// Print "Crypto ready"
// write hereSample solution
const crypto = require("node:crypto");
console.log("Crypto ready");Expected output
Crypto hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does crypto.createHash do?
crypto.createHash("sha256")- Encrypts the data
- Decrypts the data
- Generates random bytes
- Creates a hash generator Correct answer
Explanation: createHash creates a hash generator.
2 Complete the import
const crypto = require(____);
const crypto = require("node:crypto");
Explanation: node:crypto imports the crypto module.
3 Match each piece to its role
| Term | Meaning |
|---|---|
createHash |
Creates a hash |
randomBytes |
Generates random bytes |
createHmac |
Keyed hash |
createCipheriv |
Encrypts |