Hashing with node:crypto
A hash turns any input into a short string of fixed length, and the same input always gives the same string. That is how a program checks that a download arrived intact, names a version of a file and stores a password without keeping the password. node:crypto ships with Node.js and has the whole family in a few functions.
The lesson hashes a fixed text with sha256, hashes a file as its stream arrives, signs a message with a key and compares two digests without leaking how far the comparison got. The inputs are fixed and the digests are printed as they came out of the run, so a reader can compare the page with their own terminal line by line.
createHash
createHash(algorithm) makes a hash object, update adds bytes to it and digest ends it and answers with the result. The encoding of digest('hex') gives the usual sixty-four characters for sha256, and two updates with the two halves of a text give the same digest as one update with all of it, which is what makes hashing a stream possible.
The program hashes the word hello twice, once in one call and once in two, and prints both digests and the length.
The file hash.mjs:
import { createHash } from 'node:crypto';
const digest = createHash('sha256').update('hello').digest('hex');
console.log('sha256 of hello:', digest);
console.log('the digest is', digest.length, 'characters');
const inParts = createHash('sha256').update('hel').update('lo').digest('hex');
console.log('two updates give the same digest:', inParts === digest);
node hash.mjs
sha256 of hello: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
the digest is 64 characters
two updates give the same digest: true
The two digests are the same string, and the one from the page is the one every sha256 tool prints for the same input, which is a useful check of a crypto library. A hash is one way: nothing in it says the input was hello, and no amount of work on the digest gives the text back.
Hashing a stream
A file of ten gigabytes cannot be read into a string, and it does not have to be: the hash object takes one chunk at a time and keeps a small state between them. The program attaches the hash to the data event of a read stream, which is the same stream the lesson on streams built, and compares the result with the hash of the text it wrote.
The program writes a fixed text into a temporary folder, hashes the file through a stream and hashes the text directly, then prints both and the comparison.
The file stream.mjs:
import { createHash } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'hash-'));
const file = join(dir, 'notes.txt');
const text = 'alpha\nbeta\ngamma\n';
await writeFile(file, text);
const hash = createHash('sha256');
const stream = createReadStream(file);
stream.on('data', (chunk) => {
hash.update(chunk);
});
await new Promise((resolve, reject) => {
stream.on('end', resolve);
stream.on('error', reject);
});
const fromFile = hash.digest('hex');
const fromText = createHash('sha256').update(text).digest('hex');
console.log('the hash of the stream:', fromFile);
console.log('the hash of the text is the same:', fromFile === fromText);
await rm(dir, { force: true, recursive: true });
node stream.mjs
the hash of the stream: 4fdbc441ea7b546100e086ac1e4fc5ae6749b7314311c99db05be450eca12996
the hash of the text is the same: true
The two paths gave the same digest, which is the whole promise of a streaming hash. This is how a download is checked: the server publishes the digest of the file, and the client hashes the bytes as they arrive and compares at the end without ever holding the file.
HMAC
A hash says what the bytes are; an HMAC says who sent them. createHmac mixes a secret key into the hash, so only someone who has the key can produce the same signature for the same message. The digest is different for every key, and a server that checks it can reject a message that was changed in transit.
The program signs one message with two keys and prints both signatures and the comparison with the first one.
The file hmac.mjs:
import { createHmac } from 'node:crypto';
const sign = (key, message) => createHmac('sha256', key).update(message).digest('hex');
const first = sign('secret', 'the message');
console.log('the signature:', first);
console.log('the same key gives the same signature:', sign('secret', 'the message') === first);
console.log('another key gives another signature:', sign('other', 'the message'));
console.log('the two differ:', sign('other', 'the message') !== first);
node hmac.mjs
the signature: 20749b21a543edb6111867fba87cd35a060f1806a1502800292a12343c94b9bf
the same key gives the same signature: true
another key gives another signature: f4e32f357780ca25e862c8602108062cd0996fd898de38362ac892e9effb3cea
the two differ: true
The same key and the same message gave the same signature twice, and the other key gave something else entirely. The key is the secret, and it is the reason a signature is sent in a header next to a request rather than a password: the request can be verified without the secret travelling with it.
timingSafeEqual
Comparing two digests with === stops at the first byte that differs, and the time it took tells an attacker how much of a guess was right. timingSafeEqual compares every byte whatever happens, and it needs two buffers of the same length, which is a check the caller does first. It is a small function and the one place where a plain comparison is a real weakness.
The program compares two equal digests, one different digest and a buffer of the wrong length, and prints the code of the error the last one throws.
The file compare.mjs:
import { createHash, timingSafeEqual } from 'node:crypto';
const digest = (text) => createHash('sha256').update(text).digest();
const left = digest('hello');
const right = digest('hello');
console.log('the lengths:', left.length, right.length);
console.log('the two buffers are equal:', timingSafeEqual(left, right));
console.log('a different text is not equal:', timingSafeEqual(left, digest('hellp')));
try {
timingSafeEqual(left, Buffer.from('ab'));
} catch (error) {
console.log('a different length throws:', error.code);
}
node compare.mjs
the lengths: 32 32
the two buffers are equal: true
a different text is not equal: false
a different length throws: ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH
The two equal digests compared true, the different one false, and the short buffer threw before any comparison happened. A program that checks a signature therefore compares the lengths first and answers false for a mismatch, because a thrown error in a request handler is a bug and not a rejection.
Exercises
- Hash the same text with sha512 and print the digest and its length. How many characters does it have?
- Hash a string and a Buffer with the same content. Are the digests equal?
- Change one character of the message and watch the HMAC change. How many characters of the signature stay the same?
- Compare two equal digests with === and with timingSafeEqual. Which one can leak information, and how?
- Call update after digest. Which error do you get, and why is the hash object finished?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does digest("hex") return?
Answer
A string of hexadecimal characters
The encoding decides the form of the result, and hex is the form a page prints.
-
What does this program print?
import { createHash } from "node:crypto"; console.log(createHash("sha256").update("hello").digest("hex"));Answer
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
That is the sha256 digest of the five letters, and every tool prints the same string.
-
Which algorithm does the lesson use?
Answer
sha256
sha256 is the default choice for a new program, and md5 and sha1 are broken.
-
What does this program print?
import { createHash } from "node:crypto"; console.log(createHash("sha256").update("hello").digest("hex").length);Answer
64
The digest is thirty-two bytes, and every byte takes two hexadecimal characters.
-
What does an HMAC add to a hash?
Answer
A secret key, so only the key holder can sign
The key is mixed into the computation, and the same message with another key gives another signature.
-
What does this program print?
import { createHmac } from "node:crypto"; const sign = (key) => createHmac("sha256", key).update("message").digest("hex"); console.log(sign("secret") === sign("other"));Answer
false
Two different keys give two different signatures for the same message.
-
Why compare digests with timingSafeEqual?
Answer
It takes the same time whatever the position of the difference
The time of a plain comparison can tell an attacker how much of a guess was right.
-
What does this program print?
import { timingSafeEqual } from "node:crypto"; try { timingSafeEqual(Buffer.from("ab"), Buffer.from("abc")); } catch (error) { console.log(error.code); }Answer
ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH
The function needs two buffers of the same length, so the caller checks the lengths first.
-
Can a hash be reversed?
Answer
No, it only goes one way
The digest is much shorter than the input, so many inputs share one and none can be recovered.
-
What does update do?
Answer
It adds bytes to the hash and keeps the state
Many updates and one digest is what makes a hash of a stream possible.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev