randomBytes
- Node.js course
- Intermediate
- Lesson 102/116
- 5 min
Learn random bytes with crypto.randomBytes.
randomBytes
To generate cryptographically secure random bytes, use crypto.randomBytes(n). Unlike Math.random it is unpredictable; so it is suitable for password-reset tokens or session ids.
Example: crypto.randomBytes(16).toString("hex") turns 16 random bytes into a 32-character hex string. Each byte maps to two hex characters. randomBytes(8) gives 8 bytes; toString("hex") gives 16 characters. toString("base64") gives a shorter string. For a token at least 16 bytes (128 bits) is recommended; this reduces collision risk. randomBytes is synchronous; the async version has the form randomBytes(n, callback).
Use cases
Common uses of randomBytes: password-reset tokens, session ids, salts and API keys. These values must be unpredictable.
Example token: const token = crypto.randomBytes(16).toString("hex");. It gives a 32-character string; it travels safely in a URL. For salt: const salt = crypto.randomBytes(8).toString("hex");. Salt is random data added to a password hash; it makes the same password hash differently. This stops rainbow table attacks. In production you store tokens in a database and track their expiry; expired tokens are rejected.
Practice Generate a random token
Import with const crypto = require("node:crypto");. Generate a 4-byte token with const token = crypto.randomBytes(4).toString("hex");. Print the length with console.log("Byte length: " + token.length).
Starter code
// Import the crypto module
// write here
// Generate a 4-byte token
// write here
// Print "Byte length: ..."
// write hereSample solution
const crypto = require("node:crypto");
const token = crypto.randomBytes(4).toString("hex");
console.log("Byte length: " + token.length);Expected output
Bayt uzunluğu: 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
randomBytes(16) |
16 random bytes |
toString("hex") |
Hex string |
toString("base64") |
Short string |
Math.random |
Predictable |
2 How many characters does randomBytes(4).toString("hex") give?
crypto.randomBytes(4).toString("hex")- 4
- 16
- 8 Correct answer
- 2
Explanation: Each byte maps to two hex characters.
3 Complete the randomBytes call
const token = crypto.____(16).toString("hex");
const token = crypto.randomBytes(16).toString("hex");
Explanation: randomBytes(16) generates 16 random bytes.