Working with Crypto Module
1. Creating Hashes (crypto.createHash)
Example: SHA-256
import crypto from "node:crypto";
const digest = crypto.createHash("sha256").update("hello").digest("hex");
| Algorithm | Notes |
sha256 / sha512 | Recommended |
sha3-256 / sha3-512 | SHA-3 family |
blake2b512 | Fast, secure |
md5 / sha1 | INSECURE for crypto use |
2. Creating HMAC (crypto.createHmac)
Example
const sig = crypto.createHmac("sha256", secret).update(payload).digest("base64");
3. Generating Random Bytes (crypto.randomBytes)
| API | Use |
crypto.randomBytes(n) | Cryptographically secure |
crypto.randomFillSync(buf) | Fill existing buffer |
crypto.getRandomValues(typedArr) | WHATWG style |
4. Generating Random UUIDs (crypto.randomUUID)
Example
const id = crypto.randomUUID(); // RFC 4122 v4
5. Creating Secure Random Strings
Example: token
function token(bytes = 32) {
return crypto.randomBytes(bytes).toString("base64url");
}
| Encoding | Length per byte |
hex | 2 chars |
base64 | ~1.33 chars |
base64url | URL-safe variant |
6. Encrypting Data (crypto.createCipheriv)
Example: AES-256-GCM
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const enc = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
7. Decrypting Data (crypto.createDecipheriv)
Example
const dec = crypto.createDecipheriv("aes-256-gcm", key, iv);
dec.setAuthTag(tag);
const plain = Buffer.concat([dec.update(enc), dec.final()]).toString("utf8");
8. Creating Public/Private Keys (crypto.generateKeyPair)
Example
const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
const pem = privateKey.export({ type: "pkcs8", format: "pem" });
| Type | Use |
rsa | Compatibility (2048+ bits) |
ec | ECDSA (P-256, P-384) |
ed25519 | Modern, fast signatures |
x25519 | Key exchange |
9. Signing Data (crypto.sign)
| API | Use |
crypto.sign(null, data, ed25519Key) | Ed25519 (no hash) |
crypto.sign("sha256", data, rsaKey) | RSA-SHA256 |
crypto.createSign("sha256") | Streaming variant |
10. Verifying Signatures (crypto.verify)
Example
const ok = crypto.verify(null, data, publicKey, signature);
11. Using scrypt for Key Derivation
Example
const salt = crypto.randomBytes(16);
const key = await promisify(crypto.scrypt)(password, salt, 64);
| KDF | Use |
scrypt | Password hashing (memory-hard) |
pbkdf2 | Older standard |
hkdf | Derive sub-keys from existing key |
argon2 (npm) | State-of-the-art password hashing |
12. Using bcrypt for Password Hashing
Example
import bcrypt from "bcrypt";
const hash = await bcrypt.hash(password, 12);
const ok = await bcrypt.compare(input, hash);
Note: Cost factor 10–14 for modern hardware. Use argon2 for new systems.