Generating hashes, random values, and message authentication codes with crypto

Hash content, generate random identifiers and tokens, and authenticate messages with a secret key.

🎯 Introduction

By the end of this article, you will be able to verify content, generate file identifiers, and create access tokens with crypto. Examples use Node.js 24.19.0 and require no packages. Save each section separately as a .mjs file.


🧾 Hash digests: check whether content has changed

A digest helps check whether content has changed, such as when verifying a downloaded file. The same content produces the same digest. Compare your computed result with a digest supplied by a trusted source.

Use hello to simulate downloaded content and save this as hash.mjs:

import { createHash } from 'node:crypto'
const hash = createHash('sha256')
hash.update('hello', 'utf8')
const actual = hash.digest('hex')
console.log(actual)

sha256 selects the hashing algorithm; update supplies the text and utf8 specifies its encoding. digest finishes the calculation, and hex represents the result as a hexadecimal string. This example prints:

2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Suppose a trusted source publishes the following digest. Append this comparison to the same file:

const expected = '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
console.log(actual === expected ? 'Content verified' : 'Content mismatch; check again')

Run node hash.mjs. After the digest, it prints Content verified. Change the input from hello to Hello and rerun it to print Content mismatch; check again.

Create a new hash object for each independent calculation. An object that has already called digest cannot be reused for a new calculation.

A digest cannot restore the original content. The reference digest used for verification must come from a trusted source.


🏷️ randomUUID: generate storage names for uploaded files

randomUUID generates random identifiers for records or files, such as storage names for uploaded images, reducing filename collisions.

Assuming the uploaded content has already been confirmed as PNG, save this separately as file-name.mjs:

import { randomUUID } from 'node:crypto'
const fileName = `${randomUUID()}.png`
console.log(fileName)

This prints a name such as 7f52c1d2-6de8-4b4d-8c31-ae81b8bb4b10.png. The actual value usually differs on each run. UUID is a general identifier format; randomUUID returns its random version.

Use the generated name in a storage path. This code only generates a name; it does not create a file.


🎲 randomBytes: generate temporary download tokens

randomBytes generates random values that are difficult to guess, such as temporary download tokens. A token is an access credential submitted to a service when downloading.

First generate the token value. Save this separately as download-token.mjs:

import { randomBytes } from 'node:crypto'
const token = randomBytes(16).toString('hex')
console.log(token)

16 is the number of random bytes. Each byte becomes two hexadecimal characters, producing 32 characters with no fixed content.

A guessed token could be misused, so it must be unpredictable. randomBytes is suitable for security-sensitive uses; Math.random does not provide that guarantee.

The service must store the token's associated file and expiration time. When a user submits the token, the service checks it before returning the file. randomBytes only generates the value; it does not store it or manage expiration.


🔑 HMAC: check whether a received message was modified

HMAC authenticates messages between services, such as file-conversion completion notifications. It computes a value from both the message and a secret key. The recipient recomputes it and rejects the message if the values differ.

Simulate sending and verification in message-check.mjs, appending the code in this section in order.

Sender: compute the message authentication tag

import { createHmac, timingSafeEqual } from 'node:crypto'
const key = 'demo-key'
const message = 'file=report.pdf&status=ready'
const sentTag = createHmac('sha256', key).update(message, 'utf8').digest()

createHmac selects SHA-256 and the key, update supplies the message, and digest() returns a 32-byte Buffer authentication tag. demo-key is only for practice. Both parties must keep a real key secret and never send it with the message.

Recipient: recompute the tag for the received message

Append this in the same file:

const receivedMessage = message
const receivedTag = sentTag
const expectedTag = createHmac('sha256', key).update(receivedMessage, 'utf8').digest()

receivedMessage and receivedTag simulate the message and tag in a request. Compute the tag from the exact received content without reformatting it first.

Compare before deciding whether to process the message

const valid = receivedTag.length === expectedTag.length
    && timingSafeEqual(receivedTag, expectedTag)
console.log(valid ? 'Verification passed; process the message' : 'Verification failed; reject the message')

Run node message-check.mjs to print Verification passed; process the message. Change receivedMessage to the string 'file=report.pdf&status=failed', leaving receivedTag unchanged. Rerunning prints Verification failed; reject the message.

timingSafeEqual compares two equal-length Buffers and returns a boolean. It suits HMAC tag comparisons because the comparison avoids leaking timing clues based on matching prefix length. It throws for unequal lengths, so the code checks length first.

HMAC neither hides message content nor prevents replaying the same valid message.


❓ Questions and answers

Q1: Can Base64 or hexadecimal representations keep data secret?

No. They only represent bytes. Anyone who knows the rules can recover the bytes.

Q2: Why does a second digest call fail?

Calling digest ends the current calculation. Call createHash again to create a new object for other content.

Q3: Can a random identifier grant permission by itself?

No. Service rules determine authorization, not whether a string is random.


🧪 Exercise

Change the hash example's input and verify that it reports a mismatch. Then change only the received message in the HMAC example, retaining the original tag, and verify that it rejects processing.

// Write your code here

🎉 Try these techniques with your own examples!