typestar

Hashing and random values in JavaScript

Digests, UUIDs and the comparison that does not leak timing.

import { createHash, createHmac, randomUUID, randomBytes,
         timingSafeEqual } from "node:crypto";

const digest = createHash("sha256").update("lang=go&tpm=104").digest("hex");
console.log(digest.slice(0, 16), digest.length);

const signature = createHmac("sha256", "secret").update("payload")
  .digest("hex");
console.log(signature.length);

const uuid = randomUUID();
console.log(uuid.length, uuid.split("-").length);
console.log(randomBytes(8).toString("base64url").length);

const a = Buffer.from(signature);
console.log(timingSafeEqual(a, Buffer.from(signature)));

How it works

  1. createHash takes bytes or a string and produces a digest.
  2. randomUUID is the right source for an identifier.
  3. timingSafeEqual compares secrets without a timing side channel.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
565
Tokens
149
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 1 of 3 in Crypto & processes, step 15 of 18 in Node.js.

← Previous Next →