Almost every JWT you’ll meet is a JWS, a JSON Web Signature (RFC 7515): three base64url strings joined by dots, where the third one proves who made the first two. Our JWT architecture guide covers how to issue and verify those tokens safely. This article goes one level down, into the signature itself: exactly which bytes are signed, how each algorithm turns them into a signature, and the parts of the standard that rarely show up in tutorials.
We verify tokens from every common algorithm using only the Web Crypto API, make valid tokens that the issuer never produced, sign one payload twice in the same token, and sign a webhook body without copying it into the token at all. Every code example was run before publishing, against the jose library on Node.js 24, and the tokens were cross-checked with Python’s jwcrypto.
The short answer#
What the signature covers#
JSON has no single canonical form: the same object can be written with different spacing, key order, or escapes. Rather than define one, JWS sidesteps the problem. It signs the encoded text, so the verifier checks the exact characters it received before parsing anything:
// signing-input.mjs: a JWS signature covers the exact base64url text of the header and payload, not the JSON.
import { CompactSign, compactVerify } from "jose";
import { createHmac } from "node:crypto";
const key = crypto.getRandomValues(new Uint8Array(32)); // an HS256 secret
const jws = await new CompactSign(new TextEncoder().encode('{"sub":"42","admin":false}'))
.setProtectedHeader({ alg: "HS256" })
.sign(key);
const [header, payload, signature] = jws.split(".");
// The signing input is ASCII(base64url(header) + "." + base64url(payload)). Recompute the HMAC over it.
// (Comparing with === is fine for checking our understanding; a verifier needs a constant-time check, see below.)
const mine = createHmac("sha256", key).update(`${header}.${payload}`).digest("base64url");
console.log(mine === signature); // true
// The same claims with the keys in a different order: equal as JSON, different as text. The signature fails.
const reordered = Buffer.from('{"admin":false,"sub":"42"}').toString("base64url");
await compactVerify(`${header}.${reordered}.${signature}`, key).catch((e) => console.log(e.code)); // ERR_JWS_SIGNATURE_VERIFICATION_FAILEDThat has a practical consequence: verify the bytes you received. A gateway or middleware that parses a token’s payload and writes it back out, even unchanged in meaning, produces a token whose signature no longer matches. The same goes for signed webhook bodies, which we’ll get to: verify the raw request body before any JSON parser touches it.
Verifying every algorithm by hand#
A JWS library does a lot of checks, but the cryptography at its core is a single call. Here are tokens signed by jose with five algorithms, each verified with a single crypto.subtle.verify, built into Node.js, Deno, Bun, and every browser:
// by-hand.mjs: sign with jose, verify with nothing but Web Crypto, for each algorithm family.
import { CompactSign, generateKeyPair, exportJWK } from "jose";
const enc = new TextEncoder();
const b64 = (s) => Buffer.from(s, "base64url");
// How each JWS "alg" maps onto Web Crypto: the key-import parameters, then the verify parameters.
const WEBCRYPTO = {
HS256: [{ name: "HMAC", hash: "SHA-256" }, { name: "HMAC" }],
RS256: [{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, { name: "RSASSA-PKCS1-v1_5" }],
PS256: [{ name: "RSA-PSS", hash: "SHA-256" }, { name: "RSA-PSS", saltLength: 32 }],
ES256: [{ name: "ECDSA", namedCurve: "P-256" }, { name: "ECDSA", hash: "SHA-256" }],
Ed25519: [{ name: "Ed25519" }, { name: "Ed25519" }],
};
// The verifier decides the algorithm (here, a parameter). It never takes it from the token's header.
async function verifyByHand(jws, jwk, alg) {
const [header, payload, signature] = jws.split(".");
const [importParams, verifyParams] = WEBCRYPTO[alg];
const key = await crypto.subtle.importKey("jwk", jwk, importParams, false, ["verify"]);
return crypto.subtle.verify(verifyParams, key, b64(signature), enc.encode(`${header}.${payload}`));
}
const claims = enc.encode('{"sub":"42"}');
for (const alg of Object.keys(WEBCRYPTO)) {
const { privateKey, publicKey } = alg === "HS256"
? { privateKey: crypto.getRandomValues(new Uint8Array(32)) } // HMAC: one shared secret signs and verifies
: await generateKeyPair(alg);
const jwk = publicKey ? await exportJWK(publicKey) : { kty: "oct", k: Buffer.from(privateKey).toString("base64url") };
const sign = () => new CompactSign(claims).setProtectedHeader({ alg }).sign(privateKey);
const first = await sign();
const second = await sign();
const bytes = b64(first.split(".")[2]).length;
console.log(`${alg.padEnd(7)} valid: ${await verifyByHand(first, jwk, alg)}, ${bytes} bytes, ${first === second ? "same" : "different"} every time`);
}
// HS256 valid: true, 32 bytes, same every time
// RS256 valid: true, 256 bytes, same every time
// PS256 valid: true, 256 bytes, different every time
// ES256 valid: true, 64 bytes, different every time
// Ed25519 valid: true, 64 bytes, same every timeEach alg name fixes everything about the operation: the algorithm, the hash, and, for PSS, the salt length. That’s why the verifier must choose it, not read it from the token: the table maps a name you trust to parameters, and a token that names something else is rejected. (How that goes wrong is covered in the JWT guide’s flaws section.)
The five algorithm families#
alg | Web Crypto | Signature | Same every time? | Worth knowing |
|---|---|---|---|---|
HS256 | HMAC, SHA-256 | 32 bytes (43 chars) | Yes | One shared secret signs and verifies. Use at least 256 random bits. |
RS256 | RSASSA-PKCS1-v1_5 | 256 bytes (342 chars) with RSA-2048 | Yes | The most widely supported. jose refuses keys under 2048 bits. |
PS256 | RSA-PSS, salt 32 | 256 bytes (342 chars) | No: random salt | Same RSA keys as RS256, with a stronger security proof. |
ES256 | ECDSA, P-256 | 64 bytes (86 chars) | No: random nonce | Raw r || s, not DER. |
Ed25519 | Ed25519 | 64 bytes (86 chars) | Yes | Deterministic by design. Formerly written EdDSA. |
RS256 vs. PS256. Both use the same RSA key pair; they differ in the padding. PKCS #1 v1.5 is old and deterministic, and as a signature scheme it has held up in practice. PSS adds a random salt and has a security proof, which is why newer standards prefer it. RFC 7518 fixes the salt length to the hash size, 32 bytes for PS256, which is why the code passes saltLength: 32.
ES256 signatures are not DER. JWS uses the raw form: r and s as two fixed 32-byte numbers, back to back. OpenSSL, Java, and most crypto libraries produce DER by default, and a DER signature fails to verify. Web Crypto already uses the raw form; for the others, see the DER trap.
Why “same every time” matters. ECDSA needs a fresh secret number, the nonce k, for every signature. If two signatures share a nonce, anyone holding both can calculate the private key. Even nonces that are only slightly biased leak it, given enough signatures. That’s how Sony’s PlayStation 3 signing key was recovered in 2010: it used the same nonce every time. RFC 6979 avoids the problem by deriving the nonce from the key and the message, and Ed25519 was designed that way from the start, which is why its signatures repeat, and ES256’s don’t.
EdDSA or Ed25519? The original name, EdDSA (RFC 8037), didn’t say which curve. RFC 9864 (2025) registered the fully specified names Ed25519 and Ed448 and deprecated EdDSA. jose 6 accepts both; before switching, check that every verifier does. (Our Python interop test used EdDSA.)
One token, several valid spellings#
It’s tempting to treat a signed token as a fingerprint: same string, same token. It isn’t. Without the private key, anyone can produce a different string that verifies just as well:
// twins.mjs: other spellings of one token that verify too. Don't use a JWS string as a unique ID.
import { CompactSign, compactVerify, generateKeyPair } from "jose";
const { publicKey, privateKey } = await generateKeyPair("ES256");
const token = await new CompactSign(new TextEncoder().encode('{"sub":"42","jti":"a1"}'))
.setProtectedHeader({ alg: "ES256" })
.sign(privateKey);
const [header, payload, signature] = token.split(".");
const valid = (t) => compactVerify(t, publicKey).then(() => true, () => false);
// 1. ECDSA malleability: if (r, s) is a valid signature, so is (r, n - s). n is the order of the P-256 group.
const n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
const raw = Buffer.from(signature, "base64url"); // r || s, 32 bytes each
const s = BigInt("0x" + raw.subarray(32).toString("hex"));
const flipped = Buffer.concat([raw.subarray(0, 32), Buffer.from((n - s).toString(16).padStart(64, "0"), "hex")]);
const twin1 = `${header}.${payload}.${flipped.toString("base64url")}`;
// 2. Base64url slack: 64 bytes are 512 bits, but 86 characters hold 516. The last character's 4 spare bits
// are ignored when decoding, so changing them gives a different string with the same bytes.
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const last = ALPHABET.indexOf(signature.at(-1));
const twin2 = `${header}.${payload}.${signature.slice(0, -1)}${ALPHABET[last ^ 1]}`;
console.log(await valid(token), await valid(twin1), await valid(twin2)); // true true true
console.log(new Set([token, twin1, twin2]).size); // 3: three different stringsECDSA is malleable. For every valid signature (r, s), the signature (r, n − s) is valid too. That’s a property of the math, not a bug in jose: Python’s jwcrypto accepted both as well. Bitcoin nodes refuse to relay “high-s” signatures for exactly this reason. Ed25519 doesn’t have the problem: RFC 8032 requires its S value to be smaller than the group order, and the equivalent twin was rejected in all ten of our tests.
Base64url has slack. 64 bytes don’t fill 86 characters exactly, so the last character has spare bits that decoders ignore. A 32-byte HMAC signature has the same slack. Both jose and jwcrypto accepted the altered string; jose did reject a character outside the base64url alphabet.
The JSON serializations#
The compact form, header.payload.signature, is only one of three. RFC 7515 also defines two JSON forms. The general one holds one payload and a list of signatures; the flattened one holds exactly one signature. Both can carry an unprotected header, a header member that sits outside the signature:
// json.mjs: the JSON serializations. Two signatures on one payload, and a header field nobody signed.
import { GeneralSign, generalVerify, FlattenedSign, flattenedVerify, compactVerify, generateKeyPair } from "jose";
const payload = new TextEncoder().encode('{"order":1001,"amount":"49.90"}');
const payments = await generateKeyPair("ES256");
const fraud = await generateKeyPair("Ed25519");
// General: one payload and a list of signatures, each with its own header and key.
const general = await new GeneralSign(payload)
.addSignature(payments.privateKey).setProtectedHeader({ alg: "ES256", kid: "payments-1" })
.addSignature(fraud.privateKey).setProtectedHeader({ alg: "Ed25519", kid: "fraud-1" })
.sign();
console.log(general.signatures.length); // 2
console.log((await generalVerify(general, fraud.publicKey)).protectedHeader.kid); // fraud-1
// Flattened: exactly one signature. The compact form is the same three values joined with dots.
const flat = await new FlattenedSign(payload)
.setProtectedHeader({ alg: "ES256" })
.setUnprotectedHeader({ kid: "payments-1" }) // the "header" member: NOT covered by the signature
.sign(payments.privateKey);
await compactVerify(`${flat.protected}.${flat.payload}.${flat.signature}`, payments.publicKey); // valid
flat.header.kid = "attacker-key";
const { unprotectedHeader } = await flattenedVerify(flat, payments.publicKey);
console.log(unprotectedHeader.kid); // attacker-key: changed, and the token still verifiesSeveral signatures are useful when more than one party vouches for the same data, such as a payment service and a fraud check, or during a key rotation, when a token signed with both the old and the new key works with verifiers that know either one. Note what generalVerify means by success: one of the signatures verifies with the key you passed. If you require two parties, verify with each key.
The unprotected header is exactly what its name says. Changing it doesn’t affect the signature, so anything in it is a hint at best. A kid there is harmless only if it selects a key from your own key set. jose merges both headers into one result for convenience, so put alg and anything that changes the meaning of the token in the protected header, and check where a field came from before relying on it.
Detached and unencoded payloads#
Sometimes the data already travels on its own, like the body of an HTTP request, and copying it into the token would double the size. JWS has two answers. A detached payload (RFC 7515, appendix F) is signed normally, then removed from the token, leaving header..signature. An unencoded payload (RFC 7797) goes further: with b64: false, the signing input uses the raw bytes instead of their base64url, so the receiver never has to encode the body to check it:
// detached.mjs: signatures that don't carry their payload. A webhook body is signed but sent as it is.
import { CompactSign, compactVerify, FlattenedSign, flattenedVerify } from "jose";
import { createHmac } from "node:crypto";
const key = crypto.getRandomValues(new Uint8Array(32)); // shared with the webhook receiver
const body = '{"event":"invoice.paid","id":"evt_1"}';
const b64 = (s) => Buffer.from(s).toString("base64url");
// 1. Detached content (RFC 7515, appendix F): sign normally, then send the token without its middle part.
const full = await new CompactSign(new TextEncoder().encode(body)).setProtectedHeader({ alg: "HS256" }).sign(key);
const [h, , s] = full.split(".");
const signatureHeader = `${h}..${s}`; // sent next to the body, for example in an HTTP header
// The receiver puts the body it actually received back in the middle, then verifies as usual.
const [rh, , rs] = signatureHeader.split(".");
await compactVerify(`${rh}.${b64(body)}.${rs}`, key); // valid
// 2. Unencoded payload (RFC 7797): with b64: false, the signing input is the raw body, not its base64url.
const flat = await new FlattenedSign(new TextEncoder().encode(body))
.setProtectedHeader({ alg: "HS256", b64: false, crit: ["b64"] }) // b64 only takes effect when listed in crit
.sign(key);
console.log(JSON.stringify(flat.payload)); // "": jose leaves the payload out; it travels separately
console.log(createHmac("sha256", key).update(`${flat.protected}.${body}`).digest("base64url") === flat.signature); // true
await flattenedVerify({ ...flat, payload: body }, key); // valid
await flattenedVerify({ ...flat, payload: body.replace("evt_1", "evt_2") }, key)
.catch((e) => console.log(e.code)); // ERR_JWS_SIGNATURE_VERIFICATION_FAILEDA few rules come with b64: false, and jose enforces them:
- It must be listed in
crit, so a verifier that doesn’t understand it refuses the token instead of computing the wrong signing input. Withoutcrit, jose ignoredb64: falseand produced an ordinary token. - It needs the JSON form or a detached payload. A raw payload can contain dots, which would break the compact form, so jose’s
CompactSignrefuses it. - Verify the raw bytes. Signed webhooks fail most often because a framework parsed the JSON body first. Keep the raw body for verification, then parse it.
jwcrypto verified jose’s unencoded token once the body was attached, and rejected it when one character of the body changed.
crit: extensions the verifier must understand#
Issuers sometimes add their own header fields. Usually that’s harmless: a verifier that doesn’t know a field ignores it. But some fields change what the token means, such as a validity rule kept in the header. If a verifier ignored one of those, it would accept tokens the issuer meant to refuse. crit is the fix: it lists the fields the verifier must understand, and a verifier that doesn’t must reject the token:
// crit.mjs: "crit" lists header fields the verifier must understand. If it doesn't, it must reject the token.
import { compactVerify } from "jose";
import { createHmac } from "node:crypto";
const key = crypto.getRandomValues(new Uint8Array(32));
const b64 = (v) => Buffer.from(JSON.stringify(v)).toString("base64url");
// Built by hand, as an issuer with its own extension would: "only valid until" a time, outside the claims.
const header = b64({ alg: "HS256", crit: ["acme-valid-until"], "acme-valid-until": 1700000000 });
const payload = b64({ sub: "42" });
const jws = `${header}.${payload}.${createHmac("sha256", key).update(`${header}.${payload}`).digest("base64url")}`;
// The signature is fine, but jose doesn't know the extension, so it refuses the token.
await compactVerify(jws, key).catch((e) => console.log(e.code)); // ERR_JOSE_NOT_SUPPORTED
// Accept the extension only if you also enforce it.
const { protectedHeader } = await compactVerify(jws, key, { crit: { "acme-valid-until": true } });
if (Date.now() / 1000 > protectedHeader["acme-valid-until"]) console.log("expired, by its own extension");jose and jwcrypto both rejected the unknown extension. In jose, accepting it takes an explicit crit option, and declaring an extension there is a promise that your code enforces it. Don’t declare one to make an error go away.
Checking a signature yourself#
Use a library when you can. If you must check an HMAC yourself, for example in a minimal webhook handler, compare the result in constant time. A plain string comparison returns as soon as one character differs, and that timing difference can, in principle, let an attacker find a valid signature one byte at a time:
// compare.mjs: if you check an HMAC yourself, compare in constant time (or let crypto.subtle.verify do it).
import { CompactSign } from "jose";
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyHs256(token, key) {
const [header, payload, signature, extra] = token.split(".");
if (signature === undefined || extra !== undefined) return false;
const expected = createHmac("sha256", key).update(`${header}.${payload}`).digest();
const given = Buffer.from(signature, "base64url");
// Not: signature === expected.toString("base64url"), which stops at the first wrong character.
return given.length === expected.length && timingSafeEqual(given, expected);
}
const key = crypto.getRandomValues(new Uint8Array(32));
const token = await new CompactSign(new TextEncoder().encode('{"sub":"42"}')).setProtectedHeader({ alg: "HS256" }).sign(key);
console.log(verifyHs256(token, key)); // true
const [h, , s] = token.split(".");
console.log(verifyHs256(`${h}.${Buffer.from('{"sub":"1"}').toString("base64url")}.${s}`, key)); // falsecrypto.subtle.verify does the comparison internally, so the by-hand code earlier doesn’t need this. Note the other checks in verifyHs256: exactly three parts, and a signature of the expected length before comparing, because timingSafeEqual throws on buffers of different lengths.
Pitfalls and past vulnerabilities#
- Letting the token pick the algorithm.
alg: noneand RS256-to-HS256 confusion are the classic JWS bugs. Pin the algorithms in the verifier. Both are explained, with tested code, in the JWT guide. - Bugs in the verifier itself. CVE-2022-21449, the “psychic signatures” bug: Java 15 to 18 accepted an ECDSA signature of all zeros. A correct implementation must reject
rorsequal to zero; keep runtimes and libraries patched. - Nonce reuse in ECDSA, as in the PS3 case: one repeated nonce exposes the private key. Use a maintained library, or Ed25519.
- Re-serializing before verifying: the token, or a detached body, must be checked exactly as received.
- Trusting the unprotected header, or treating “one signature verified” as “all parties signed”.
- Using the token string as an ID, defeated by the twins above.
- Reading a JWS as private. A signature hides nothing; anyone can decode the payload. For confidentiality, see JWS vs. JWE and the mechanics of JWE.
FAQ#
Why is the payload base64url-encoded at all?
So the compact form is a single URL-safe string with no characters that need escaping in a header, cookie, or query string, and so the signing input is unambiguous. When those don’t matter, RFC 7797’s b64: false skips the encoding.
Which algorithm should I use?
For tokens checked by several services, use an asymmetric algorithm: Ed25519 if every verifier supports it, otherwise ES256, or RS256 where compatibility matters most. HS256 only when the signer and the verifier are the same service, or share a secret by design. The trade-offs are covered in the JWT guide.
Can I compare two tokens to see if they’re the same?
Not reliably. ES256 and PS256 tokens with identical contents differ every time they’re signed, and any token can have twins. Compare verified claims instead.
How do I inspect a token’s signature?
Our JWT tool decodes the header and payload and verifies the signature using a secret, a PEM key, or a JWKS. To see the raw signature bytes, paste the third part into the Base64 decoder with the URL-safe alphabet.
Try it in your browser
- JWT Decoder, Encoder & Editor: decode a signed token’s header and payload, and verify its signature with a secret, PEM key, or JWKS.
- Base64 Encoder / Decoder: decode one part of a token with the URL-safe alphabet and see the exact bytes that were signed.
- JWE Decoder, Encoder & Editor: for the encrypted counterpart: a token whose claims nobody else can read.