← Foundations path
.NETFoundations 29 / 37Reported by candidates

Signing keys: HMAC vs RSA

“How is a JWT signed, and what is the difference between HS256 and RS256?”

Why nobody can change a token without the API noticing, and who holds which key.

See it

1/7The issuer signs the header and claims with a key. The signature goes on the end of the token.

In plain words

A JWT (JSON Web Token), the token our APIs accept, is three parts joined by dots: a header, the claims, and a signature. The header and claims are only encoded: rewritten as text that anyone can turn back, no key needed. They are not encrypted, which would lock them with a key. So anyone who holds the token can read them. The signature stops changes, not reading. The issuer, the sign-in service that creates the token, computes the signature from the header and claims using a secret key. If one letter of the claims changed, say CreditOfficer became Admin, the signature no longer fits and the API rejects the token. There are two kinds of keys. HMAC (HS256) uses one shared secret: the same secret signs, and the API recomputes the signature and compares. So every service that can check a token could also make one. RSA (RS256) uses a key pair: a private key that only the issuer keeps, to sign, and a public key that anyone may have. The API can't recompute anything with a public key. Instead the public key works like a test the signature passes or fails: it verifies a signature but can't make a valid one. That is why uses RS256 and publishes its public keys for every API to download.

Say it in the interview

What they ask next

Interviewers check that you can explain every line. Tap a question to open it.

Traps

Read more: RFC 7519: JSON Web Token · Configure JWT bearer authentication in ASP.NET Core