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");
AlgorithmNotes
sha256 / sha512Recommended
sha3-256 / sha3-512SHA-3 family
blake2b512Fast, secure
md5 / sha1INSECURE 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)

APIUse
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");
}
EncodingLength per byte
hex2 chars
base64~1.33 chars
base64urlURL-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" });
TypeUse
rsaCompatibility (2048+ bits)
ecECDSA (P-256, P-384)
ed25519Modern, fast signatures
x25519Key exchange

9. Signing Data (crypto.sign)

APIUse
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);
KDFUse
scryptPassword hashing (memory-hard)
pbkdf2Older standard
hkdfDerive 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.