crypto
The crypto module provides cryptographic functionality, including wrappers for hashing, HMAC, ciphers, key derivation, signatures, and secure random values.
API Surface
Hashing
crypto.createHash(algorithm)— create hash object..update(data),.digest([encoding]).
HMAC
crypto.createHmac(algorithm, key)— keyed-hash for auth.
Random
crypto.randomBytes(size[, callback])— secure random buffer.crypto.randomUUID()— random UUID v4.
Key Derivation
crypto.pbkdf2(password, salt, iterations, keylen, digest, cb).- Promise API:
crypto.pbkdf2Sync,crypto.scrypt.
Cipher / Decipher
crypto.createCipheriv(algorithm, key, iv)— encrypt.crypto.createDecipheriv(algorithm, key, iv)— decrypt.
Signing / Verifying
crypto.createSign(algorithm),.update(data),.sign(privateKey).crypto.createVerify(algorithm),.update(data),.verify(publicKey, sig).
Key Generation
crypto.generateKeyPair(type, options, callback)— async key pair.crypto.generateKeyPairSync(type, options)— sync.
Examples (English only)
const crypto = require("crypto");
// Hashing
const hash = crypto.createHash("sha256").update("hello").digest("hex");
console.log("sha256:", hash);
// HMAC
const hmac = crypto.createHmac("sha256", "secret").update("data").digest("hex");
console.log("hmac:", hmac);
// Random
console.log("uuid:", crypto.randomUUID());
console.log("random bytes:", crypto.randomBytes(8).toString("hex"));
// Symmetric encrypt/decrypt
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
let enc = cipher.update("secret text", "utf8", "hex");
enc += cipher.final("hex");
const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
let dec = decipher.update(enc, "hex", "utf8");
dec += decipher.final("utf8");
console.log("decrypted:", dec);
Notes
- Use modern algorithms like sha256, sha512, aes-256-gcm.
- Avoid weak algorithms (MD5, DES).
- Keys and IVs must have correct lengths for chosen cipher.
- Use
randomBytesfor cryptographic randomness, notMath.random(). - For password storage, prefer scrypt or argon2 over raw hash.