REGEXVAULTv2.0
Security/API Keys & Tokens
Verified Safe

JWT Header (Decoded Algorithm Field) Regex for Go

/^\{"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 Go. 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 Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.

Go Implementation

Go
// JWT Header (Decoded Algorithm Field)
// ReDoS-safe | RegexVault — Security > API Keys & Tokens

package validation

import "regexp"

var jwtHeaderDecodedAlgorithmFieldRe = regexp.MustCompile(`^\{"alg":"(HS256|HS384|HS512|RS256|RS384|RS512|ES256|ES384|ES512|PS256|PS384|PS512|EdDSA)","typ":"JWT"(?:,"kid":"[^"]{1,100}")?\}$`)

func ValidateJwtHeaderDecodedAlgorithmField(s string) bool {
    return jwtHeaderDecodedAlgorithmFieldRe.MatchString(s)
}

// Example
// fmt.Println(ValidateJwtHeaderDecodedAlgorithmField("{"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 Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. 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