1. Random UUID
randomUUID() returns a cryptographically strong RFC 4122 v4 UUID string — ideal for unique ids.
const id = randomUUID();Typorithm · medium
Step 1 of 8 · intro card
Core Modules
node:crypto gives you secure primitives: randomUUID() and randomBytes() for ids and tokens, createHash for one-way hashing, createHmac for keyed signatures, and scrypt (with a random salt) for password hashing. Never roll your own crypto.
randomUUID() returns a v4 UUID and randomBytes(n) returns cryptographically secure random bytes — use them for ids, tokens, and salts instead of Math.random().
Hashing uses the update/digest pattern: createHash("sha256").update(data).digest("hex") for a plain one-way hash, and createHmac("sha256", secret).update(data).digest("hex") when you need a keyed signature that can be verified but not forged.
For passwords, never use a fast hash like sha256 directly — use scrypt with a per-user random salt, which is intentionally slow and memory-hard to resist brute force. The golden rule: never roll your own crypto, lean on these vetted primitives.
randomUUID() and randomBytes() generate secure ids and tokens.
createHash for hashing; createHmac adds a secret key.
Use scrypt with a salt for passwords — never a plain hash.
import { randomUUID, randomBytes, createHash, createHmac, scrypt } from "node:crypto";
const id = randomUUID(); // RFC 4122 v4 UUID
const token = randomBytes(32).toString("hex"); // 256-bit secret
const digest = createHash("sha256").update("hello").digest("hex");
const sig = createHmac("sha256", secret).update(payload).digest("hex");
const salt = randomBytes(16);
scrypt(password, salt, 64, (err, key) => {
store(salt.toString("hex"), key.toString("hex")); // never store the password
});Connect each part of the code to the concept before you type.
randomUUID() returns a cryptographically strong RFC 4122 v4 UUID string — ideal for unique ids.
const id = randomUUID();randomBytes(n) returns n cryptographically secure random bytes; .toString("hex") makes a 2n-char token.
randomBytes(32).toString("hex")createHash picks the algorithm, .update feeds the data, and .digest("hex") returns the fixed-length hash.
createHash("sha256").update("hello").digest("hex")createHmac mixes a secret key into the hash so the digest can be verified but not forged without the key.
createHmac("sha256", secret).update(payload).digest("hex")scrypt is a deliberately slow, salted key-derivation function for passwords — far safer than a plain hash.
scrypt(password, salt, 64, (err, key) => {Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.