jwt

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package jwt provides functions for decoding, verifying, creating, and re-signing JSON Web Tokens (JWTs). It wraps github.com/golang-jwt/jwt/v5 with a simpler API suited for tooling, testing, and security research.

Index

Constants

View Source
const (
	// MinRSABits is the smallest RSA modulus size allowed. 2048 bits is the
	// floor recommended by NIST SP 800-57 and RFC 7518 for RS*/PS* algorithms.
	MinRSABits = 2048
	// DefaultRSABits is used when the caller does not pick an RSA key size.
	DefaultRSABits = 2048
)

Key-generation security defaults and lower bounds.

Variables

View Source
var RegisteredClaimDescriptions = map[string]string{

	"iss": "Issuer — who created and signed the token",
	"sub": "Subject — the principal the token is about",
	"aud": "Audience — intended recipient(s) of the token",
	"exp": "Expiration Time — token must be rejected after this time",
	"nbf": "Not Before — token must be rejected before this time",
	"iat": "Issued At — when the token was created",
	"jti": "JWT ID — unique identifier for the token",

	"alg":  "Algorithm — how the token is signed (or \"none\")",
	"typ":  "Type — media type of the token, typically \"JWT\"",
	"cty":  "Content Type — media type of the payload, if nested",
	"kid":  "Key ID — hints which key was used to sign the token",
	"jku":  "JWK Set URL — where to fetch the signer's public keys",
	"jwk":  "JSON Web Key — the signer's public key, embedded inline",
	"x5c":  "X.509 Certificate Chain — embedded signer certificate(s)",
	"x5u":  "X.509 URL — where to fetch the signer's certificate",
	"x5t":  "X.509 Certificate SHA-1 Thumbprint",
	"crit": "Critical — extensions that must be understood to process the token",
}

RegisteredClaimDescriptions maps well-known JWT claim and header names to a short human-readable description, used to annotate decoded tokens.

View Source
var TimeClaimNames = map[string]bool{
	"exp": true,
	"nbf": true,
	"iat": true,
}

TimeClaimNames lists registered claims that hold a NumericDate (Unix timestamp) value, per RFC 7519.

Functions

func AsTime added in v0.9.0

func AsTime(v interface{}) (time.Time, bool)

AsTime attempts to interpret a decoded claim value as a Unix timestamp, as used by the exp/nbf/iat claims. It returns false if the value isn't a plausible numeric timestamp.

func Create

func Create(opts CreateOptions, signingKey interface{}) (string, error)

Create builds and signs a new JWT using the provided options and signing key. The key type must match the algorithm family: []byte for HMAC, *rsa.PrivateKey for RS*/PS*, and *ecdsa.PrivateKey for ES*.

func CreateWithSecret

func CreateWithSecret(opts CreateOptions, secret []byte) (string, error)

CreateWithSecret builds and signs a new JWT using an HMAC secret.

func FetchJWKS

func FetchJWKS(uri string) (jwtlib.Keyfunc, error)

FetchJWKS retrieves a JWKS from a remote URI and returns a Keyfunc that selects the matching key by kid header, falling back to alg-based matching when no kid is present. Supported key types: RSA (kty=RSA) and EC (kty=EC). The URI is passed without modification; callers should use HTTPS in production.

func FindAll added in v0.7.0

func FindAll(text string) []string

FindAll scans text and returns every unique JWT found within it, preserving discovery order. Only structurally valid JWTs (parseable header and payload) are returned; look-alikes that cannot be decoded are silently skipped.

func FindAllReader added in v0.7.0

func FindAllReader(r io.Reader) ([]string, error)

FindAllReader reads all content from r and delegates to FindAll.

func GenerateKey

func GenerateKey(method jwt.SigningMethod) (interface{}, error)

GenerateKey generates a random cryptographic key appropriate for the given signing method. The returned key type depends on the algorithm family:

  • HMAC (HS256/HS384/HS512): []byte of length 64
  • RSA (RS256/RS384/RS512/PS256/PS384/PS512): *rsa.PrivateKey (2048-bit)
  • ECDSA ES256: *ecdsa.PrivateKey (P-256)
  • ECDSA ES384: *ecdsa.PrivateKey (P-384)
  • ECDSA ES512: *ecdsa.PrivateKey (P-521)
  • none: returns (nil, nil)

func IsJWT

func IsJWT(token string) bool

IsJWT reports whether s looks like a well-formed JWT.

func LoadPrivateKeyFromPEM

func LoadPrivateKeyFromPEM(pemData []byte) (interface{}, error)

LoadPrivateKeyFromPEM parses PEM-encoded private key data and returns the key. Supported PEM block types:

  • "PRIVATE KEY" (PKCS#8): RSA, EC, or Ed25519
  • "RSA PRIVATE KEY" (PKCS#1): RSA only
  • "EC PRIVATE KEY" (SEC 1): EC only

func LoadPublicKeyFromPEM

func LoadPublicKeyFromPEM(pemData []byte) (interface{}, error)

LoadPublicKeyFromPEM parses PEM-encoded public key data and returns the key. Supported PEM block types:

  • "PUBLIC KEY" (PKIX/SPKI): RSA, EC, or Ed25519
  • "RSA PUBLIC KEY" (PKCS#1): RSA only

func ParseSigningMethod

func ParseSigningMethod(alg string) (jwtlib.SigningMethod, error)

ParseSigningMethod returns the jwt.SigningMethod for the given algorithm name.

Types

type CreateOptions

type CreateOptions struct {
	Algorithm  string            // Signing algorithm name (e.g. "HS256", "RS256", "ES256").
	Claims     map[string]string // Custom payload claims; values are auto-parsed to int64, bool, or string.
	Expiration time.Duration     // If > 0, sets the "exp" claim relative to now.
	NotBefore  time.Duration     // If > 0, sets the "nbf" claim relative to now.
	IssuedAt   bool              // If true, sets the "iat" claim to the current Unix time.
}

CreateOptions holds parameters for creating a new JWT.

type DecodedJWT

type DecodedJWT struct {
	Header    map[string]interface{} // Decoded JOSE header (e.g. alg, typ, kid).
	Claims    map[string]interface{} // Decoded payload claims.
	Signature string                 // Raw base64url-encoded signature segment.
	Raw       string                 // Original token string as received.
}

DecodedJWT holds the decoded parts of a JWT token.

func Decode

func Decode(tokenString string) (*DecodedJWT, error)

Decode parses a JWT token string without verifying the signature. It returns an error only if the token is structurally malformed.

type DiffResult added in v0.9.0

type DiffResult struct {
	Base  string      `json:"base"`
	Diffs []TokenDiff `json:"diffs"`
}

DiffResult is the outcome of comparing a base token against one or more other tokens.

func Diff added in v0.9.0

func Diff(base string, others ...string) (*DiffResult, error)

Diff decodes base and each of others, then reports, for each of others, which header/claims keys were added, removed, or changed relative to base, plus whether the signature differs. It returns an error if any token fails to decode.

type FieldChange added in v0.9.0

type FieldChange struct {
	Key    string      `json:"key"`             // Header or claim name.
	Status string      `json:"status"`          // One of "added", "removed", "changed".
	Base   interface{} `json:"base,omitempty"`  // Value on the base token; absent when Status is "added".
	Other  interface{} `json:"other,omitempty"` // Value on the compared token; absent when Status is "removed".
}

FieldChange describes how a single header or claim key differs between the base token and a compared token.

type GenerateKeyOptions added in v0.7.0

type GenerateKeyOptions struct {
	// Algorithm is the JWA name the key is generated for: HS256/384/512,
	// RS256/384/512, PS256/384/512, ES256/384/512 or EdDSA.
	Algorithm string
	// RSABits selects the RSA modulus size. Ignored for non-RSA algorithms.
	// Zero means DefaultRSABits. Values below MinRSABits are rejected.
	RSABits int
	// SecretBytes selects the HMAC secret length in bytes. Ignored for
	// asymmetric algorithms. Zero means "match the HMAC output size"
	// (32/48/64 for HS256/384/512). Shorter values are rejected because a
	// secret weaker than the MAC output size reduces the security margin.
	SecretBytes int
}

GenerateKeyOptions holds the user-chosen parameters for key generation.

type GeneratedKey added in v0.7.0

type GeneratedKey struct {
	Algorithm string

	// Asymmetric algorithms populate these. PrivateKey is the crypto key
	// value; PrivatePEM/PublicPEM are PKCS#8 / PKIX PEM encodings.
	PrivateKey any
	PublicKey  any
	PrivatePEM []byte
	PublicPEM  []byte

	// HMAC algorithms populate this with the raw random secret.
	Secret []byte
}

GeneratedKey is the result of GenerateKeyPair.

func GenerateKeyPair added in v0.7.0

func GenerateKeyPair(opts GenerateKeyOptions) (*GeneratedKey, error)

GenerateKeyPair creates fresh key material for the given algorithm using the crypto/rand CSPRNG, enforcing minimum-strength parameters while letting the caller pick sizes above the floor.

func (*GeneratedKey) EncodeSecret added in v0.7.0

func (g *GeneratedKey) EncodeSecret(format SecretFormat) (string, error)

EncodeSecret renders the generated HMAC secret in the requested format.

type OrderedMapClaims

type OrderedMapClaims struct {
	jwt.Claims
	Raw string // Original token string used to recover claim insertion order.
}

OrderedMapClaims wraps jwt.Claims and preserves the original claim order when marshaling. This ensures that re-signed tokens maintain the same claim ordering as the source token.

func NewOrderedMapClaims

func NewOrderedMapClaims(token *jwt.Token) *OrderedMapClaims

NewOrderedMapClaims creates an OrderedMapClaims from a parsed token.

func (OrderedMapClaims) MarshalJSON

func (m OrderedMapClaims) MarshalJSON() ([]byte, error)

MarshalJSON serializes claims in the original key order.

type SecretFormat added in v0.7.0

type SecretFormat string

SecretFormat controls how a generated HMAC secret is encoded for output.

const (
	SecretFormatBase64URL SecretFormat = "base64url" // unpadded, URL-safe (default)
	SecretFormatBase64    SecretFormat = "base64"    // standard, padded
	SecretFormatHex       SecretFormat = "hex"
	SecretFormatRaw       SecretFormat = "raw" // raw bytes, no encoding
)

type TokenDiff added in v0.9.0

type TokenDiff struct {
	Token            string        `json:"token"`            // The compared token, as passed in.
	Header           []FieldChange `json:"header"`           // Header (JOSE) differences, sorted by key.
	Claims           []FieldChange `json:"claims"`           // Claims (payload) differences, sorted by key.
	SignatureChanged bool          `json:"signatureChanged"` // Whether the raw signature segment differs from the base.
	IdenticalToBase  bool          `json:"identical"`        // True when header, claims, and signature all match the base.
}

TokenDiff holds the differences between the base token and one other token.

type VerifyOptions

type VerifyOptions struct {
	Secret  []byte //nolint:gosec // HMAC secret (for HS256, HS384, HS512).
	KeyPEM  []byte // PEM-encoded public key bytes (RSA, EC, or Ed25519); a private key is also accepted and the public part is extracted.
	JWKSURI string // URL of a JWKS endpoint; the matching key is selected by kid, falling back to alg.
}

VerifyOptions holds the configuration for token verification. Exactly one of Secret, KeyPEM, or JWKSURI must be set.

type VerifyResult

type VerifyResult struct {
	Valid     bool                   // True only when the signature and all standard claims are valid.
	Claims    map[string]interface{} // Decoded payload claims; populated even when Valid is false.
	Algorithm string                 // Signing algorithm extracted from the token header.
	Error     error                  // Verification error when Valid is false; nil when Valid is true.
}

VerifyResult contains the outcome of a token verification attempt.

func Verify

func Verify(tokenString string, opts VerifyOptions) (*VerifyResult, error)

Verify validates the given JWT token using the provided options. It returns (result, nil) even when the signature is invalid — the failure reason is captured in result.Error and result.Valid is false. A non-nil returned error indicates a structural problem (malformed token or missing key).

Directories

Path Synopsis
checks/fuzz
Package fuzz implements the "jwtop crack --fuzz" claim-mutation check: it complements the fixed exploit checks in jwt/crack/checks/ by mutating every claim in the token (type confusion, oversized strings, special characters, null) and comparing each response against a captured reference response, flagging any that diverge (5xx status, a leaked stack trace, or a body length far from the reference).
Package fuzz implements the "jwtop crack --fuzz" claim-mutation check: it complements the fixed exploit checks in jwt/crack/checks/ by mutating every claim in the token (type confusion, oversized strings, special characters, null) and comparing each response against a captured reference response, flagging any that diverge (5xx status, a leaked stack trace, or a body length far from the reference).
checks/timestamp_tampering
Package timestamptampering implements the "jwtop crack" check for the exp/iat/nbf timestamp-tampering exploits in jwt/exploit: using the HMAC secret recovered by the secret (weak_secret) check, it re-signs the token with its exp claim pushed into the past and sends it.
Package timestamptampering implements the "jwtop crack" check for the exp/iat/nbf timestamp-tampering exploits in jwt/exploit: using the HMAC secret recovered by the secret (weak_secret) check, it re-signs the token with its exp claim pushed into the past and sends it.
Package exploit provides standalone JWT security exploit functions.
Package exploit provides standalone JWT security exploit functions.
external
Package external wraps the optional john-the-ripper and hashcat CLI tools as alternative HMAC-secret crackers, for use when the built-in in-process dictionary brute-force (jwt/exploit.CrackSecret) doesn't find the secret.
Package external wraps the optional john-the-ripper and hashcat CLI tools as alternative HMAC-secret crackers, for use when the built-in in-process dictionary brute-force (jwt/exploit.CrackSecret) doesn't find the secret.
Package fuzz generates claim-mutation payloads for the "jwtop crack --fuzz" mode: type confusion, oversized strings, special characters, and explicit nulls applied to each claim of a JWT, so a live server can be probed for parsing bugs (crashes, stack traces, wildly different response sizes) that the fixed check set in jwt/crack/checks/ doesn't exercise.
Package fuzz generates claim-mutation payloads for the "jwtop crack --fuzz" mode: type confusion, oversized strings, special characters, and explicit nulls applied to each claim of a JWT, so a live server can be probed for parsing bugs (crashes, stack traces, wildly different response sizes) that the fixed check set in jwt/crack/checks/ doesn't exercise.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址