← Java / Spring · Contents

JAVA-047 / Advanced

Weak JWT signing keys or using a public key as an HMAC key (key confusion)

A02:2021 Cryptographic Failures · CWE-327 · CWE-347

Why is this a problem?

Tokens can be forged if the HS256 key is short or the RS256 public key is used as an HMAC secret.

How to fix it

java
SecretKey k = Keys.secretKeyFor(SignatureAlgorithm.HS256);   // Automatically generate a sufficiently long key and store it in an environment variable
// Alternatively, sign with RS256 and a private key; verify using only the public key and fix the algorithm

Further reading