Skip to content
Blog

← All articles

Nonces Explained: One Word, Four Different Rules

A nonce is a “number used once”, but AES-GCM, CBC, ECDSA, Content Security Policy, OpenID Connect and replay protection each need something different from it: unique, unpredictable, secret, or remembered. Runnable Node code for each, including a forged AES-GCM message from two that shared a nonce, a PIN recovered through predictable CBC IVs, and a CSP nonce tested in Chrome.

By 16 min read

“Nonce” is short for number used once, and it borrows from the old English phrase “for the nonce”: for this one occasion. The idea sounds simple enough to fit in one rule: never use the same value twice. But the word turns up in a cipher, a signature algorithm, a browser security header, a sign-in protocol and a replay check, and each of them needs something different from it. Some only need it to be unique, so a counter is perfect. Some need it to be unpredictable, so a counter is a vulnerability. One needs it to be secret as well. And a nonce that stops replays is useless unless the server remembers it.

Most nonce bugs come from applying the rule from one place in another. This article goes through each, with runnable Node code and the attack that follows when the rule is broken: a forged AES-GCM message, a PIN read through a predictable CBC IV, and a Content Security Policy nonce defeated in Chrome. Two of these mistakes already have their own articles: reusing a nonce with AES-GCM in Encrypting Data in JavaScript, and the PS3 key recovered from a repeated ECDSA nonce in Elliptic Curves for Programmers.

Prefer video? There’s a thirteen-minute version that walks through each rule and attack. All the code is also on GitHub, with tests that run every example in Node.js and the CSP attack in Chrome: nonce-sample.

Nothing loads from YouTube until you press play. Watch on YouTube

The short answer#

One word, four rules#

Unique (a counter is fine)

Where: AES-GCM, ChaCha20-Poly1305 and other stream-based AEADs

Get it wrong: One repeat leaks the XOR of two plaintexts and lets an attacker forge messages

Unique and unpredictable

Where: CBC IVs, CSP nonces, the OpenID Connect nonce, state, DPoP server nonces, WebAuthn challenges

Get it wrong: If an attacker can guess the next one, it stops protecting anything

Unique, secret and unbiased

Where: ECDSA’s per-signature k (and DSA’s)

Get it wrong: A repeat, a leak or even a slight bias gives away the private key

Fresh, and remembered by the server

Where: Replay protection: signed requests, Digest auth, DPoP proofs, jti

Get it wrong: Without server-side state, a copied request works again

The same word, four requirements. A counter meets the first and fails the second; a random value meets the first two and fails the fourth unless something remembers it.

The table also explains the neighbours that get confused with nonces. An IV (initialization vector) is the older name for a cipher’s per-message input; for GCM and ChaCha20 it’s the same thing as the nonce, and for CBC it’s an IV with a stricter rule, as we’ll see. A salt in password hashing is unique per password but not secret, and it doesn’t need to be fresh: it’s stored and reused for every check of that password. A JWT’s jti is a unique ID that a replay store remembers, which makes it a nonce of the fourth kind.

Unique: AES-GCM and ChaCha20#

AES-GCM and ChaCha20-Poly1305 turn the key and nonce into a stream of random-looking bytes and XOR it with your data. Encrypt two messages with the same key and nonce and they share that stream, so XORing the two ciphertexts gives the XOR of the two plaintexts. That much is well known, and the symmetric encryption article runs it.

The worse part is the tag. GCM’s 16-byte tag is a polynomial in a secret value H, which is AES of an all-zero block under your key, evaluated in a field of 2128 elements where addition is XOR. For a single 16-byte message with no associated data, it works out as:

Dividing gives H², a square root gives H, and then S follows from either message. That’s all an attacker needs to compute a valid tag for any ciphertext they like. With one known plaintext, they get the keystream too, and can choose what the forged message says:

gcm-forgery.mjs
// gcm-forgery.mjs: two AES-GCM messages under the same key and nonce are enough to forge a third.
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";

// The server's mistake: one nonce for every message (a constant, or a counter that restarted).
const key = randomBytes(32), nonce = randomBytes(12);
function encrypt(text) {
  const c = createCipheriv("aes-256-gcm", key, nonce);
  const ct = Buffer.concat([c.update(text, "utf8"), c.final()]);
  return { ct, tag: c.getAuthTag() };
}
function decrypt({ ct, tag }) {
  const d = createDecipheriv("aes-256-gcm", key, nonce).setAuthTag(tag);
  return Buffer.concat([d.update(ct), d.final()]).toString("utf8"); // throws if the tag is wrong
}

// GCM's tag is a polynomial in a secret H = AES(key, 0), computed in GF(2^128). XOR is addition there; this is multiplication.
const big = (b) => BigInt("0x" + b.toString("hex"));
const buf = (x) => Buffer.from(x.toString(16).padStart(32, "0"), "hex");
function mul(x, y) {
  let z = 0n;
  for (let i = 127n; i >= 0n; i--) {
    if ((x >> i) & 1n) z ^= y;
    y = y & 1n ? (y >> 1n) ^ (0xe1n << 120n) : y >> 1n;
  }
  return z;
}
function pow(x, e) {
  let r = 1n << 127n; // the field's 1
  for (; e > 0n; e >>= 1n, x = mul(x, x)) if (e & 1n) r = mul(r, x);
  return r;
}

// The attacker sees two one-block messages (16 bytes each) and their tags. For one block, tag = C·H² ⊕ L·H ⊕ S,
// where L is the lengths block and S = AES(key, nonce‖1). Same nonce, same S, so XORing the two tags cancels it:
const a = encrypt("to:alice amt:100");
const b = encrypt("to:bob   amt:250");
const H2 = mul(big(a.tag) ^ big(b.tag), pow(big(a.ct) ^ big(b.ct), 2n ** 128n - 2n)); // divide
const H = pow(H2, 2n ** 127n); // square root: squaring is one-to-one in this field
const L = 128n; // no associated data, 128 bits of ciphertext
const S = big(a.tag) ^ mul(big(a.ct), H2) ^ mul(L, H);
const realH = createCipheriv("aes-256-ecb", key, null).update(Buffer.alloc(16));
console.log("recovered H = AES(key, 0):", buf(H).equals(realH));

// Knowing the first plaintext gives the keystream, so the attacker chooses the text as well as a valid tag.
const forged = Buffer.from("to:eve amt:99999").map((x, i) => x ^ a.ct[i] ^ "to:alice amt:100".charCodeAt(i));
const tag = buf(mul(big(forged), H2) ^ mul(L, H) ^ S);
console.log("the server decrypts the forgery:", decrypt({ ct: forged, tag }));
recovered H = AES(key, 0): true
the server decrypts the forgery: to:eve amt:99999

The forged ciphertext and tag go through Node’s own createDecipheriv, which checks the tag and accepts it. We ran it ten times with fresh keys and nonces, and it worked every time. Note what the attacker didn’t need: the key. Two ciphertexts and their tags gave up H, and from then on every message with that nonce can be forged. This is Antoine Joux’s “forbidden attack” from 2006. In 2016, Böck and others scanned the internet and found HTTPS servers repeating GCM nonces in TLS, which let anyone in the network path inject content into their pages.

Longer messages give a polynomial of higher degree, and the attacker finds its roots instead of dividing, which is more work but still fast. The fix is never the attack; it’s keeping nonces unique.

Counters or random?

For this kind of nonce, uniqueness is the only requirement, so a counter is ideal: it can’t repeat until it wraps. TLS 1.3 does exactly that, XORing a per-record sequence number into a fixed IV. The difficulty is keeping the counter unique when processes restart, run in parallel, or get restored from a snapshot. The 2017 KRACK attack on WPA2 Wi-Fi worked by tricking devices into reinstalling a key, which reset its nonce counter to zero.

Random nonces avoid the bookkeeping, but random values can collide. The birthday bound tells you how likely that is:

birthday.mjs
// birthday.mjs: the chance that random nonces repeat under one key, p = 1 − e^(−n² / 2^(bits+1)).
const p = (n, bits) => -Math.expm1(-(n * n) / 2 ** (bits + 1));
const show = (x) => (x > 0.001 ? `${(x * 100).toFixed(1)}%` : `1 in ${(1 / x).toExponential(1)}`);

console.log("messages per key   96-bit nonce (AES-GCM)   192-bit nonce (XChaCha20)");
for (const e of [32, 40, 48]) console.log(`2^${e}`.padEnd(19), show(p(2 ** e, 96)).padEnd(24), show(p(2 ** e, 192)));
messages per key   96-bit nonce (AES-GCM)   192-bit nonce (XChaCha20)
2^32                1 in 8.6e+9              1 in 6.8e+38
2^40                1 in 1.3e+5              1 in 1.0e+34
2^48                39.3%                    1 in 1.6e+29

That’s why NIST limits a key to 232 messages (about four billion) when GCM nonces are random. Most applications never get near it. If yours might, rotate keys, use a counter you can trust, or switch to XChaCha20-Poly1305, whose 192-bit nonce makes random nonces safe at any volume. If you can’t trust where nonces come from at all, AES-GCM-SIV (RFC 8452) is built so that a repeated nonce reveals only whether two messages were identical.

Unpredictable: the CBC IV#

CBC mode, the common choice before GCM, XORs each plaintext block with the previous ciphertext block before encrypting it, and the first block with the IV. Its IV must be unique, like a GCM nonce, but that’s not enough: it must also be unpredictable. If an attacker knows the next IV and can get their own text encrypted, they can check guesses about an earlier block.

The trick is to cancel the IVs. The secret block was encrypted as AES(secret ⊕ IV₁). If the attacker submits guess ⊕ IV₁ ⊕ IV₂ and the server encrypts it with IV₂, CBC computes AES(guess ⊕ IV₁), which equals the secret’s ciphertext exactly when the guess is right. Here it is against a four-digit PIN, with the IV taken from a counter and then from a random generator:

cbc-predictable-iv.mjs
// cbc-predictable-iv.mjs: CBC needs an IV the attacker can't predict. With a counter, they can test guesses.
import { createCipheriv, randomBytes, randomInt } from "node:crypto";

const key = randomBytes(16);
const block = (text) => Buffer.from(text.padEnd(16, "."));
const xor = (a, b, c) => a.map((x, i) => x ^ b[i] ^ c[i]);
const plusOne = (iv) => Buffer.from((BigInt("0x" + iv.toString("hex")) + 1n).toString(16).padStart(32, "0"), "hex");

function attack(makeIv) {
  const encrypt = (plain) => {
    const iv = makeIv();
    const c = createCipheriv("aes-128-cbc", key, iv).setAutoPadding(false);
    return { iv, ct: Buffer.concat([c.update(plain), c.final()]) };
  };
  // Someone's secret: the attacker sees its IV and ciphertext on the wire.
  const secret = encrypt(block(`pin=${String(randomInt(10000)).padStart(4, "0")}`));

  // The attacker can get their own text encrypted (a form field, a message) and expects the next IV to be the last + 1.
  // CBC encrypts block ⊕ IV, so sending guess ⊕ oldIV ⊕ nextIV gives AES(guess ⊕ oldIV): the secret's ciphertext if the guess is right.
  let last = secret.iv;
  for (let pin = 0; pin < 10000; pin++) {
    const guess = block(`pin=${String(pin).padStart(4, "0")}`);
    const mine = encrypt(xor(guess, secret.iv, plusOne(last)));
    if (mine.ct.equals(secret.ct)) return `found ${guess.toString().slice(0, 8)} after ${pin + 1} guesses`;
    last = mine.iv;
  }
  return "not found in 10000 guesses";
}

let counter = BigInt(randomInt(1e9));
console.log("counter IV:", attack(() => Buffer.from((counter++).toString(16).padStart(32, "0"), "hex")));
console.log("random IV: ", attack(() => randomBytes(16)));
counter IV: found pin=8848 after 8849 guesses
random IV:  not found in 10000 guesses

A counter is unique, never repeats, and gave the PIN away. A random IV made the same attack useless. This isn’t hypothetical: TLS 1.0 used the last ciphertext block of the previous record as the next IV, and the 2011 BEAST attack used this to read session cookies from HTTPS traffic, guessing one byte at a time by lining the cookie up against a block boundary. TLS 1.1 had already switched to a random IV for each record; BEAST is what pushed everyone to upgrade.

Secret and unbiased: ECDSA’s k#

An ECDSA signature uses a fresh random number k for each signature, and the specification calls it a nonce too. It has the strictest rule of all: unique, unpredictable, secret, and uniformly random. Sign two messages with the same k and the private key falls out of two subtractions and a division; that’s how the PlayStation 3’s signing key leaked in 2010, and the elliptic curves article runs the attack on real P-256 keys.

Repeats happen outside games consoles too: in 2013, a flaw in Android’s SecureRandom made some Bitcoin wallet apps reuse k, and their coins were taken. Worse, unlike a GCM nonce, k doesn’t even have to repeat to leak the key. If a few bits of each k are known, enough signatures let a lattice algorithm recover the key; the 2019 TPM-FAIL attack got those bits from how long signing took. The modern answer is to take k out of the random generator’s hands: Ed25519 and deterministic ECDSA (RFC 6979) derive it from a hash of the private key and the message. Node’s crypto and Web Crypto never let you choose k, so this is a risk only in hand-written signing code or a weak hardware random generator.

The CSP nonce#

A Content Security Policy can tell the browser to run only the scripts that carry a nonce. The server picks a new random value for each response, puts it in the header (script-src 'nonce-…'), and adds nonce="…" to every <script> tag it wrote. Script injected through an XSS bug doesn’t have it, so the browser refuses to run it. Here, a page with a deliberate XSS bug, protected by a nonce:

csp-nonce.mjs
// csp-nonce.mjs: a new nonce for every response, in the header and on each script you wrote.
import { createServer } from "node:http";
import { randomBytes } from "node:crypto";

const fixed = randomBytes(16).toString("base64");
const STATIC = process.argv.includes("--static"); // the mistake, to compare: one nonce for every page

createServer((req, res) => {
  const nonce = STATIC ? fixed : randomBytes(16).toString("base64"); // 128 bits from a CSPRNG
  const q = new URL(req.url, "http://localhost").searchParams.get("q") ?? "";
  res.setHeader("Content-Security-Policy", `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`);
  res.setHeader("Content-Type", "text/html; charset=utf-8");
  res.setHeader("Cache-Control", "no-store"); // a cached page would hand the same nonce to everyone
  // q is echoed without escaping on purpose: the page has an XSS bug, and the CSP is the second line of defense.
  res.end(`<!doctype html><title>CSP nonce</title>
<p id="status">injected script: blocked</p>
<p>You searched for: ${q}</p>
<script nonce="${nonce}">console.log("the page's own script ran");</script>`);
}).listen(process.env.PORT ?? 4290);

We loaded it in Chrome with a script injected through q that changes the status line, and tried three versions of the attack:

ServerInjected scriptIn Chrome
New nonce per responseNo nonceBlocked (the page’s own script ran)
New nonce per responseThe nonce from an earlier pageBlocked
Static nonce (--static)The nonce from an earlier pageRan

With a new nonce per response, a nonce read from an earlier page is useless, because the next response has a different one. With a static nonce, the attacker reads it from any page, puts it on their script tag, and the CSP lets it through. The nonce is in the HTML source for anyone to see, so this nonce is about being unpredictable for the next response, not secret.

A static nonce usually isn’t written on purpose. It happens when:

  • The HTML is cached. A CDN or a server cache that stores a page stores its nonce too, and hands it to every visitor. That’s why the example sends Cache-Control: no-store; if you need caching, use a CSP with hashes of your scripts instead.
  • The site is statically generated. A nonce baked into an HTML file at build time is the same for everyone. Static sites need hash-based policies, or a nonce added by the server or CDN at request time.
  • It’s generated once at startup, as in the --static mode above, or per session instead of per response.

'strict-dynamic' lets scripts that carry the nonce load other scripts, so bundlers and tag managers keep working without listing every host. And a CSP nonce is a second line of defense: it doesn’t fix the XSS bug, which in this page is echoing q without escaping it.

state, nonce and PKCE in OpenID Connect#

An OpenID Connect sign-in sends three random values that are easy to mix up. The nonce is the one named after the concept: the app generates it, keeps it in the user’s session, and sends it in the authorization request; the identity provider copies it into the ID token; the app checks that it matches. That ties each ID token to the sign-in that asked for it:

oidc-nonce.mjs
// oidc-nonce.mjs: the nonce ties an ID token to the sign-in that asked for it.
import { SignJWT, generateKeyPair, jwtVerify } from "jose";
import { randomBytes } from "node:crypto";

// A stand-in identity provider: it copies the nonce from the authorization request into the ID token.
const idp = await generateKeyPair("ES256");
const issue = (sub, nonce) =>
  new SignJWT({ nonce }).setProtectedHeader({ alg: "ES256" }).setIssuer("https://idp.test").setAudience("my-app")
    .setSubject(sub).setIssuedAt().setExpirationTime("5m").sign(idp.privateKey);

// Starting sign-in: a fresh, unguessable nonce, kept in this browser's session (with state and the PKCE verifier).
function startSignIn(session) {
  session.nonce = randomBytes(16).toString("base64url");
  return `https://idp.test/authorize?client_id=my-app&response_type=code&scope=openid&nonce=${session.nonce}`;
}

// Back from the provider: verify the signature and claims, then compare the nonce and forget it.
async function finishSignIn(session, idToken) {
  const { payload } = await jwtVerify(idToken, idp.publicKey, { issuer: "https://idp.test", audience: "my-app" });
  const expected = session.nonce;
  delete session.nonce; // one use
  if (!expected || payload.nonce !== expected) throw new Error("nonce mismatch");
  return payload.sub;
}

const tryIt = async (label, session, token) => {
  try { console.log(label, "accepted, signed in as", await finishSignIn(session, token)); }
  catch (e) { console.log(label, "rejected:", e.message); }
};
const alice = {}, mallory = {};
startSignIn(mallory);
const mallorysToken = await issue("mallory", mallory.nonce); // valid and signed, but from Mallory's own sign-in

startSignIn(alice);
const alicesToken = await issue("alice", alice.nonce);
await tryIt("Alice's token:  ", alice, alicesToken);
await tryIt("the same again: ", alice, alicesToken);
startSignIn(alice);
await tryIt("Mallory's token:", alice, mallorysToken);
Alice's token:   accepted, signed in as alice
the same again:  rejected: nonce mismatch
Mallory's token: rejected: nonce mismatch

Mallory’s ID token is genuine, signed by the provider, unexpired and for the right audience, and it’s still rejected, because it came from Mallory’s own sign-in. That stops an attacker who has a valid token, their own or a stolen one, from injecting it into someone else’s sign-in. And because the app forgets the nonce after one use, the same token can’t be replayed into the same session either.

ValueWho checks itWhat it stops
stateThe app, when the browser comes backCSRF on the redirect: an attacker’s sign-in response landing in your browser
nonceThe app, inside the ID tokenAn ID token from another sign-in being injected or replayed
PKCE code_verifierThe identity provider, at the token endpointA stolen or injected authorization code being exchanged by someone else

The protections overlap: the OAuth security best practice (RFC 9700) lets a client rely on PKCE against CSRF when the provider supports it, and lets confidential OpenID Connect clients use the nonce instead of PKCE against code injection. In practice, send all three; frameworks do it by default. ASP.NET Core’s OpenID Connect handler, used in our BFF sample, generates and checks the nonce (kept in a short-lived cookie) and the state (tied to a correlation cookie) for you. All three must be unpredictable, which is why they come from a cryptographic random generator and not a counter.

Replay protection: nonces the server remembers#

The last kind of nonce stops a captured request from being sent again: a signed webhook, a DPoP proof, a payment request. The rule here isn’t about how the nonce is made; it’s that the server must remember which ones it has seen. A unique, unpredictable nonce that nobody checks stops nothing.

Remembering forever doesn’t scale, so the nonce is paired with a timestamp. The server rejects anything outside a time window, and only needs to remember the nonces inside it:

replay-window.mjs
// replay-window.mjs: a nonce plus a timestamp. The timestamp limits how long the nonces must be remembered.
const WINDOW = 5 * 60_000; // accept requests up to 5 minutes old (or early, for clock skew)
const seen = new Map(); // nonce -> when it can be forgotten

function accept(nonce, sentAt, now) {
  for (const [n, until] of seen) if (until < now) seen.delete(n); // in production: Redis SET NX with a TTL
  if (Math.abs(now - sentAt) > WINDOW) return "rejected, outside the window";
  if (seen.has(nonce)) return "rejected, replay";
  seen.set(nonce, sentAt + WINDOW); // after this, the timestamp check rejects it anyway
  return "accepted";
}

const t = Date.UTC(2026, 10, 23, 12, 0, 0), s = 1000;
console.log("new request:              ", accept("n-7f3a", t, t));
console.log("same request, 1 s later:  ", accept("n-7f3a", t, t + s));
console.log("a request 6 minutes old:  ", accept("n-91c2", t - 360 * s, t));
console.log("first again, 5 min later: ", accept("n-7f3a", t, t + 301 * s));
console.log("nonces remembered now:    ", seen.size);
new request:               accepted
same request, 1 s later:   rejected, replay
a request 6 minutes old:   rejected, outside the window
first again, 5 min later:  rejected, outside the window
nonces remembered now:     0

The detail that matters is when a nonce can be forgotten: when its timestamp leaves the window, not five minutes after the server saw it. From then on, the timestamp check rejects the request without the store. In production, the store is shared by every instance: a Redis SET key NX with a TTL is the usual choice, as in our article on running a jti replay store in production.

The same idea, with the roles shifted, appears in several protocols:

  • Server-issued nonces. In DPoP, the server can send a DPoP-Nonce header and reject proofs that don’t include it, with a use_dpop_nonce error. Because the server chose it, the client can’t sign proofs in advance. HTTP Digest authentication and WebAuthn challenges work the same way: the server picks a random value and checks it comes back once.
  • Client-chosen IDs. A JWT’s jti or a webhook’s message ID is chosen by the sender and remembered by the receiver, with the token’s expiry playing the part of the timestamp.

How to make a nonce#

  • For anything that must be unpredictable, use 16 random bytes from a CSPRNG: crypto.randomBytes(16) in Node, crypto.getRandomValues(new Uint8Array(16)) in the browser, RandomNumberGenerator.GetBytes(16) in .NET, secrets.token_bytes(16) in Python. Encode as base64url if it goes in a URL or header. 128 bits can’t be guessed and won’t collide.
  • Never Math.random(). It isn’t designed to be unpredictable, and its output can be predicted from a few earlier values; see CSPRNG vs Math.random.
  • Never a timestamp alone. It’s predictable, and two requests in the same millisecond share it.
  • For encryption nonces, let the library or a proven scheme decide. A random 96-bit nonce per message within the 232 limit, a counter you can guarantee never resets, or XChaCha20’s 192 bits.
  • A UUID is fine only if it’s random. crypto.randomUUID() gives a version 4 UUID with 122 random bits, which is enough. Version 1 and version 7 UUIDs contain a timestamp, so they’re partly predictable; see UUID v4 vs v7.

What we tested#

Every code block above is in the article’s examples file, and a test script extracts them unchanged and runs them on Node 24 in Docker, checking what each prints:

  • The GCM forgery ran ten times with new keys and nonces: H matched AES(key, 0) each time, and Node’s AES-GCM decrypted the forged message.
  • The CBC attack ran five times with random PINs: the counter IV gave away the PIN every time (after PIN + 1 guesses), and the random IV never did.
  • The OpenID Connect check accepted the right token once and rejected the replayed and injected ones, with real ES256 tokens from jose.
  • The CSP server sent a 128-bit nonce that matched between header and script and changed on each of three responses, and the same nonce every time with --static. The blocking itself was checked in Chrome, as in the table above.
  • The birthday table and the replay window print exactly what’s shown.

FAQ#

Does a nonce need to be secret?

Usually not. GCM nonces, CBC IVs, CSP nonces and OpenID Connect nonces are all sent in the clear. What they need is to be unique and, for most of them, unpredictable before they’re used. ECDSA’s k is the exception: it must stay secret forever, which is why it never leaves the signing code.

What’s the difference between a nonce, an IV and a salt?

For GCM and ChaCha20, nonce and IV are two names for the same input. CBC’s IV must also be unpredictable. A salt is for password hashing: unique per password, stored with the hash, and reused every time that password is checked, so it isn’t “used once” at all.

How long should a nonce be?

For cipher nonces, the length is fixed by the algorithm: 12 bytes for AES-GCM and ChaCha20-Poly1305, 24 for XChaCha20, 16 for a CBC IV. For random values that must not be guessed (CSP, OpenID Connect, challenges), 16 bytes is the usual choice; the WebAuthn specification asks for challenges of at least 16 bytes.

What is the nonce in Bitcoin mining?

A different use of the word: a 32-bit field in the block header that miners change until the block’s hash falls below the target. It needs to be neither unique nor unpredictable; it’s just the part of the input they’re free to vary.

Can I see the nonce in a token?

Yes. Paste an ID token into our JWT decoder and the nonce claim is in the payload, next to iss, aud and sub. A DPoP proof that answers a server’s challenge carries it as nonce too.

Get the code

  • nonce-sample on GitHub: every example in this article, with tests that run the GCM forgery, the CBC attack, the OpenID Connect check and the replay window in Node.js, and the CSP attack in Chrome.

Try it in your browser

  • Encrypt & Decrypt: encrypt with AES-GCM or ChaCha20-Poly1305 and a nonce you choose, and see that the same key and nonce give the same keystream.
  • JWT Decoder, Encoder & Editor: decode an ID token to find its nonce claim, or a DPoP proof to find the server’s nonce.
  • UUID Generator: see how many random bits each UUID version has before using one as a nonce.