Content integrity checks
Verify that an incoming payload matches a known digest before processing it.
Node.js · Module
The node:crypto module provides Node.js access to cryptographic operations including hashes, HMACs, encryption, decryption, signing, and verification. Its APIs wrap functionality supplied by OpenSSL.
Import the module with the node:crypto specifier, then use its APIs to create cryptographic objects such as hashes, HMACs, ciphers, decipher streams, signers, and verifiers. These objects consume data through update-style methods and produce results through operations such as digest, final, sign, or verify.
import * as crypto from 'node:crypto';node:crypto built-in-module specifier.createHash() as the factory for producing hash objects.getHashes() lets code inspect digest algorithms supported by the current runtime.import { createHash } from 'node:crypto';
const digest = createHash('sha256')
.update('hello')
.digest('hex');
console.log(digest);Creates a SHA-256 hash of a string and prints its hexadecimal digest.
Verify that an incoming payload matches a known digest before processing it.
Generate or validate keyed message authentication codes for trusted messages.
Encrypt, decrypt, sign, or verify data using supported cryptographic primitives.
The node:crypto module exposes cryptographic functionality backed by wrappers around OpenSSL. Its documented areas include hashing, HMAC, encryption and decryption, signing, and signature verification.
Follow-up: How would you hash data incrementally? Create a hash with createHash(), pass chunks to hash.update(), then call hash.digest() to obtain the result.
Use createHash(algorithm) to obtain a Hash instance. Feed data with update() and finalize it with digest(), optionally requesting an encoding such as hexadecimal.
Follow-up: What should be checked before selecting an algorithm? Use the documented supported-algorithm information rather than assuming every OpenSSL algorithm is available in the runtime.
The module can be unavailable in a Node.js build. In that case, importing from node:crypto or calling require('node:crypto') throws an error, so applications should account for runtime support when necessary.
Follow-up: What is a practical way to detect this condition? Load the module during startup and handle the import or require failure before attempting cryptographic operations.
createHash()createHmac()HashHmacCipherDecipherSignVerify