Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Standard Library and Web APIs

Web Crypto, Randomness and Timers

Use the Web Crypto API in Deno for random values, UUIDs, SHA hashes, HMAC signatures and AES-GCM encryption, plus timers, performance.now and Intl date formatting - all runnable examples.

Deno ships the browser's Web Crypto API, so hashing, signing and encryption need no dependency and no --allow-* flag. Next to it you find the timing tools every program needs: setTimeout, setInterval, performance.now() and date formatting with Intl. Everything on this page is standard JavaScript, so the examples run as written, on Deno, Node.js and in a browser.

Security code is easy to get subtly wrong. Treat this lesson as a tour of the building blocks, and prefer well-reviewed libraries for anything involving passwords or keys in production.

Random values and UUIDs

Math.random() is fine for games and shuffling, and never for secrets. For tokens, session ids and keys use crypto:

Node.js Secure random numbers and UUIDs

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.

The loop in randomInt avoids modulo bias: taking random % max favours small numbers unless you discard values from the incomplete last block. The standard library also has @std/uuid and @std/ulid for other identifier formats.

Hashing

A hash function turns any data into a fixed-size fingerprint. The same input always gives the same output; a different input gives a different output with overwhelming probability, and you cannot go backwards. crypto.subtle.digest supports SHA-1 (avoid), SHA-256, SHA-384 and SHA-512:

Node.js SHA-256 hashing

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.

Hashes verify file integrity and build content-addressed names. They are not enough for storing passwords: those need a slow, salted algorithm such as Argon2, scrypt or bcrypt from a vetted library. The @std/crypto package extends digest with more algorithms (for example BLAKE3) and streaming input.

To hash a large file without loading it, stream it:

TypeScript
using file = await Deno.open("big.iso");
const digest = await crypto.subtle.digest("SHA-256", file.readable);

Passing a stream to digest is a Deno extension of the standard API.

HMAC: signing with a secret

An HMAC proves a message came from someone who knows a secret key and was not altered. It is how webhooks and signed cookies work:

Node.js Sign and verify with HMAC

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.

Always use verify (or a constant-time comparison) rather than comparing signature strings with ===.

Encrypting data with AES-GCM

AES-GCM is an authenticated encryption mode: it hides the content and detects tampering. The rules: a fresh random IV (nonce) for every message, and never reuse one with the same key.

Node.js Encrypt and decrypt with AES-GCM

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.

Store the IV with the ciphertext (it is not secret). Key management, meaning where the key lives and how it rotates, is the hard part of cryptography, not the API calls. Never hard-code a key in source code; read it from an environment variable (Command-Line Arguments and Environment Variables) or a secrets manager.

crypto.subtle also supports RSA, ECDSA, Ed25519 and ECDH for asymmetric keys, PBKDF2 and HKDF for deriving keys, and exportKey/importKey for JWK and raw formats.

Timers

The timer functions are the browser ones:

TypeScript
const id = setTimeout(() => console.log("once, later"), 1000);
clearTimeout(id);

const tick = setInterval(() => console.log("every second"), 1000);
setTimeout(() => clearInterval(tick), 3500);

Timer callbacks never run exactly on time: the delay is a minimum, and a busy event loop postpones them. Open timers and intervals keep the program alive, so clear them, or use Deno.unrefTimer(id) for background timers that should not block exit.

Node.js Timers, order and measuring

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.

The output order shows the event loop at work: synchronous code first, then microtasks (promises), then timers. performance.now() gives a high-resolution, monotonic clock, which is the right tool for measuring durations; Date.now() can jump when the system clock changes. For benchmarks use deno bench (Testing and Tooling).

Dates and Intl

Date is old and awkward, but fine for timestamps, and Intl formats them for any language:

Node.js Formatting dates and numbers with Intl

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.

Store and transmit dates as UTC ISO strings (toISOString()), and convert to a time zone only for display. Newer Deno versions also support the Temporal API, a modern replacement for Date, behind a flag or by default depending on release; check the release notes for your version.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which should you use to generate a session token?

    crypto.getRandomValues is cryptographically secure; Math.random is predictable.
  2. 2. Why should you not store passwords with plain SHA-256?

    General hashes are designed to be fast. Password hashing must be deliberately slow and salted.
  3. 3. What must be true of the IV in AES-GCM?

    Reusing an IV with the same key breaks the security of GCM. It is not secret but must be unique.
  4. 4. Which clock is best for measuring how long code takes?

    performance.now() is monotonic and high resolution, unaffected by system clock changes.
  5. 5. Which permission does crypto.subtle.digest need?

    Web Crypto runs purely in memory and needs no permission.

Summary

  • Use crypto.randomUUID() and crypto.getRandomValues() for secure randomness, never Math.random().
  • crypto.subtle.digest hashes; hashes alone are wrong for passwords.
  • HMAC signs and verifies messages; use verify.
  • AES-GCM encrypts and detects tampering; use a fresh IV for each message and keep keys out of source code.
  • Timers are browser-standard; the event loop runs sync code, then microtasks, then timers.
  • Use performance.now() to measure and Intl to format dates, numbers and lists.

You have finished the language, modules and standard library chapters. Next you will build servers.

Next: HTTP Servers with Deno.serve