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.
import { hash } from 'node:crypto'; console.log(hash('sha256', 'hello')); // hex string
Try it
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.
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
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
Bufferfirst. - Defaults to hex, not a
Buffer. This differs fromdigest()without arguments, which returns aBuffer. Pass'buffer'to get bytes. - No keyed or extendable output. Use
createHmac()for keys, andcreateHash('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.