JWT Header (Decoded Algorithm Field) Regex for Java
/^\{"alg":"(HS256|HS384|HS512|RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512|EdDSA)","typ":"JWT"(?:,"kid":"[^"]{1,100}")?\}$/What this pattern does
This page provides a comprehensive, battle-tested regular expression for matching jwt header (decoded algorithm field), ported and verified for Java. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.
Java Implementation
// JWT Header (Decoded Algorithm Field)
// ReDoS-safe | RegexVault — Security > API Keys & Tokens
import java.util.regex.Pattern;
public class JwtHeaderDecodedAlgorithmFieldValidator {
private static final Pattern PATTERN =
Pattern.compile("^\\{\"alg\":\"(HS256|HS384|HS512|RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512|EdDSA)\",\"typ\":\"JWT\"(?:,\"kid\":\"[^\"]{1,100}\")?\\}$");
public static boolean validate(String input) {
return PATTERN.matcher(input).matches();
}
// Example
public static void main(String[] args) {
System.out.println(validate("{"alg":"HS256","typ":"JWT"}")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
{"alg":"HS256","typ":"JWT"} | {"alg":"none","typ":"JWT"} |
{"alg":"RS256","typ":"JWT","kid":"key-id-12345"} | {"alg":"HS256"} |
{"alg":"ES256","typ":"JWT"} | {"alg":"RS256","typ":"jwt"} |
| — | {"typ":"JWT","alg":"RS256"} |
When to use this pattern
This pattern is drawn from the Security > API Keys & Tokens category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
The algorithm confusion attack (CVE class) occurs when the verifier is tricked into using a different algorithm than intended. Always specify and enforce the expected algorithm in your verification code — never trust the algorithm from the token header.
Technical Notes
Explicitly excludes 'none' and weak algorithms (HS1, MD5). Approved algorithms: HMAC-SHA (HS256/384/512), RSA PKCS#1 v1.5 (RS*), ECDSA (ES*), RSA-PSS (PS*), EdDSA. The 'kid' (key ID) claim is optional. JSON key order is enforced — real parsers should be order-agnostic.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern