crypto Module (Node.js)

crypto is Node.js's built-in module for cryptography: hashing, HMAC, encryption, and generating secure random values. It is used for checksums, signing, and creating tokens or random ids.

Node.js

The crypto module wraps OpenSSL to provide cryptographic primitives without external packages. Common uses are hashing data (crypto.createHash('sha256')), computing message authentication codes (createHmac), symmetric and asymmetric encryption, and generating cryptographically secure random bytes with crypto.randomBytes.

For random identifiers and tokens, crypto is the safe choice — Math.random() is not cryptographically secure and must never be used for tokens, session ids, or password-reset codes. crypto.randomUUID() produces a standard UUID, and crypto.randomBytes(n).toString('hex') gives a random hex token.

Note the distinction from password hashing: general hashes like SHA-256 are fast and fine for checksums and HMAC, but for storing passwords you use a deliberately slow, salted algorithm like bcrypt or crypto's own scrypt, not a plain SHA hash.

Syntax

crypto.randomBytes(32).toString("hex")

Examples

JavaScript

const crypto = require("crypto");

// a secure random token
const token = crypto.randomBytes(16).toString("hex");

// a SHA-256 checksum
const hash = crypto.createHash("sha256").update("data").digest("hex");
console.log(crypto.randomUUID());

Learn it in a lesson

See also

Back to the Dictionary