Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท crypto

Node.js crypto.hash() method

Reference for crypto.hash() in Node.js: compute a digest of a string or buffer in one call, choose the output encoding, and know when createHash() is still needed.

crypto.hash(algorithm, data[, outputEncoding]) computes a digest of data you already have in memory, in a single synchronous call. It replaces the three-step createHash(...).update(...).digest(...) pattern for the common case and is noticeably faster for small inputs, because it skips creating a stream-like Hash object.

It was added in Node.js 21.7 and 20.12, so it is available in current LTS releases. For data that arrives in chunks or for a very large file, crypto.createHash() is still the right tool.

NODE
import { hash } from 'node:crypto';
console.log(hash('sha256', 'hello'));   // hex string

Try it

Node.js One call, several encodings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Errors and a cache-key helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
crypto.hash(algorithm, data[, outputEncoding])   // string | Buffer
Name Description
algorithm Digest name such as 'sha256', 'sha512', 'sha3-256', 'sha1' or 'md5'.
data A string (always read as UTF-8), Buffer, typed array or DataView.
outputEncoding 'hex' (default), 'base64', 'base64url', 'latin1', or 'buffer' to get a Buffer.

Returns: a string in the chosen encoding, or a Buffer when outputEncoding is 'buffer'.

Errors: an unsupported algorithm throws an Error whose message says the digest method is not supported. A data value that is not a string or binary type throws ERR_INVALID_ARG_TYPE.

Usage notes

  • Synchronous and in memory. The whole input must already be in memory. Do not use it on data that can be gigabytes; stream it through createHash() instead.
  • Strings are always UTF-8. To hash text in another encoding, convert it to a Buffer first.
  • Defaults to hex, not a Buffer. This differs from digest() without arguments, which returns a Buffer. Pass 'buffer' to get bytes.
  • No keyed or extendable output. Use createHmac() for keys, and createHash('shake256', { outputLength }) for variable-length output.
  • Same security caveats as any hash. SHA-256 or stronger for anything security related; fast hashes are not password storage.
  • Ideal for cache keys, ETags and content addresses, where inputs are small and many.
  • Older Node.js versions lack it. Fall back to createHash() if you must support Node.js 18.