❯ehsan.blog
~/blog/your-jwt-verifier-accepts-a-512-bit-key — zsh
❯cat your-jwt-verifier-accepts-a-512-bit-key.md

Your hand-rolled JWT verifier accepts a 512-bit key

·6 min read

Your hand-rolled JWT verifier accepts a 512-bit key — article card for a post by Ehsan Shahid

You decided not to add a JWT library. It is three base64 pieces and a signature — you have crypto.subtle built in, so you wrote it yourself.

Someone hands your service a token. You verify it:

js
const ok = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', publicKey, sig, input)

ok is true. The signature really does match the key.

The key is 512 bits long. That is small enough that the signature proves almost nothing — and nothing in that line of code will ever mention it.

The whole thing in one file

js
const enc = new TextEncoder()
const b64u = (b) => Buffer.from(b).toString('base64url')

const { privateKey, publicKey } = await crypto.subtle.generateKey(
  {
    name: 'RSASSA-PKCS1-v1_5',
    modulusLength: 512,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: 'SHA-256',
  },
  true,
  ['sign', 'verify'],
)

const header = b64u(enc.encode(JSON.stringify({ alg: 'RS256', typ: 'JWT' })))
const body = b64u(enc.encode(JSON.stringify({ sub: 'admin' })))
const input = enc.encode(`${header}.${body}`)
const sig = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', privateKey, input)

const ok = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', publicKey, sig, input)

console.log('key size:', privateKey.algorithm.modulusLength, 'bits')
console.log('verify says:', ok)
plaintext
key size: 512 bits
verify says: true

No warning when the key was made. No warning when it signed. No warning when it verified. Three chances to say something, three silences.

Why Web Crypto does not care

This is not a bug. It is a boundary between two specs, and once you see the boundary the whole thing stops being surprising.

Web Crypto is a general-purpose crypto toolbox. Its job is RSA, correctly. It is used for file signing, licence checks, encrypted messages, and plenty of things where a short key is a deliberate choice — an old format you have to stay compatible with, a test fixture, a demo. So Web Crypto does what you told it to do and keeps its opinions to itself.

JWT is a different spec, written by different people, for one narrow job: tokens that decide who you are. That spec, RFC 7518, is blunt about key size:

A key of size 2048 bits or larger MUST be used with these algorithms.

That sentence appears four times in the document, once for each RSA family. It is a rule about JWTs. Web Crypto has never heard of JWTs.

flowchart LR
  A["your code"] --> B["crypto.subtle<br/>'is this signature valid<br/>for this key?'"]
  B --> C["true"]
  A -.->|"nobody asks"| D["RFC 7518<br/>'is this key big enough<br/>to be a JWT key?'"]

The check exists. It just lives in a document, and documents do not run.

Where a real library puts it

I went and read jose, the JWT library most Node and Edge projects end up on, to see where it handles this. Version 6.2.14, src/lib/jws_sign.ts, right before it signs anything:

ts
const signingKey = await rawKey(await prepareKey(entry, key, 'sign'), entry.subtle, 'sign')
if (entry.minRsaBits) checkModulusLength(entry.alg, signingKey)

checkModulusLength is five lines, in src/lib/key.ts:

ts
export function checkModulusLength(alg: string, key: types.CryptoKey): void {
  const { modulusLength } = key.algorithm as RsaKeyAlgorithm
  if (typeof modulusLength !== 'number' || modulusLength < 2048) {
    throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`)
  }
}

That is the entire difference between the library and your version. One if, reading a number that was sitting on the key object the whole time.

Hand the token from the demo above to jose instead of to your own verifier:

plaintext
TypeError: RS256 requires key modulusLength to be 2048 bits or larger

It refuses on the signing side and the verifying side — jws_verify.ts has the identical line. And minRsaBits: 2048 is attached to every RSA entry in its algorithm table, so RS256, RS384, RS512, PS256, PS384 and PS512 all get it. I tried PS256 with a 1024-bit key and got the same refusal.

The part that fooled me

I assumed a library would catch this when you load the key. That is where I would have put it. So I tested it:

js
const imported = await importJWK({ ...jwk, alg: 'RS256' }, 'RS256')
// no error — a 1024-bit key imports perfectly fine

Importing a weak key succeeds. Nothing is wrong with the key as a key — it is a real, valid RSA public key, and importJWK is just turning JSON into a CryptoKey.

The complaint only arrives when you try to use it as a JWT key. That timing matters for a practical reason: you cannot catch this problem when you fetch a JWKS and cache it. If you want to know before the first request comes in, you have to look at the size yourself.

How a 512-bit key gets into a real system

Nobody chooses 512 bits on purpose today. It arrives sideways:

  • A key generated years ago, when 1024 bits was normal, still sitting in a config because rotating it was never anyone’s ticket.
  • A partner’s JWKS endpoint. You verify tokens with their key, and their key strength is their decision, made on their timeline.
  • A tutorial snippet with modulusLength: 1024 because it generates faster, copied into a test, then copied out of the test.
  • A .env on staging that quietly became the .env on production.

Your own code never changes. The key does.

Three lines to check yours

If your public key arrives as a JWK — from a JWKS endpoint, from a config file — the size is in there already. n is the modulus, base64url-encoded, so its decoded byte count times eight is the key size:

js
const bits = Buffer.from(jwk.n, 'base64url').length * 8
console.log('key is', bits, 'bits ->', bits >= 2048 ? 'fine' : 'TOO SMALL')
plaintext
key is 512 bits -> TOO SMALL

If you already have a CryptoKey, it is simpler — key.algorithm.modulusLength is the number, no decoding needed.

Run it where you load the key, not where you verify. A startup log line saying which bit size you are trusting is worth more than a check buried in a request handler nobody reads.

The short version

  • Web Crypto will generate, sign with, and verify a 512-bit RSA key and report success at every step. Tested on Node v22.16.0.
  • RFC 7518 requires 2048 bits or larger for every RSA JWT algorithm. That rule lives in the spec, not in the crypto API.
  • jose enforces it in five lines (checkModulusLength), called on both the sign and the verify path, for all six RSA algorithms.
  • Importing a weak key never throws. The error comes at sign or verify time, so you cannot catch it when you cache a JWKS.
  • Node’s WebCrypto refused to generate anything below 512 bits for me — 256 and 384 both failed with OperationError. 512 went through.
  • Writing your own JWT verifier is not mainly about the base64 and the signature call. It is about the rules in the spec that no API enforces for you.

The other thing that struck me reading jose 6 is what is missing from it: the whole Node-versus-browser split its earlier versions carried. I counted the 200 files it deleted once Node shipped a crypto global.

Everything above came from running it: Node v22.16.0 on Linux, jose 6.2.14.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.