jwgo

package module
v0.0.0-...-31fc273 Latest Latest
Warning

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

Go to latest
Published: May 24, 2025 License: MIT Imports: 17 Imported by: 0

README

Genocide Watch

jwgo logo

jwgo is a Go library for efficient creation and parsing of JSON web tokens.

Go Reference Tests Go Report Card License

Installation

Install jwgo using the go get command:

go get -u github.com/alvii147/jwgo

Usage

Once installed, jwgo can be used to both encode and decode JWTs.

Encoding

jwgo.NewEncoder can be used to encode a given payload:

package main

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/alvii147/jwgo"
)

func main() {
	issuedAt := time.Now().UTC().Unix()
	expirationTime := time.Now().UTC().AddDate(0, 0, 1).Unix()
	notBefore := time.Now().UTC().AddDate(0, 0, -1).Unix()

	payload := &jwgo.Payload{
		Issuer:         "pickle",
		Subject:        "rick",
		Audience:       []string{"foo"},
		ExpirationTime: &expirationTime,
		NotBefore:      &notBefore,
		IssuedAt:       &issuedAt,
		JWTID:          "42",
	}
	key := []byte("deadbeef")
	signer := jwgo.NewHS256(key)

	var w strings.Builder
	err := jwgo.NewEncoder(&w, signer).Encode(payload)
	if err != nil {
		fmt.Fprint(os.Stderr, "encoding failed", err)
	}

	fmt.Println(w.String())
	// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJwaW...
}

Decoding

jwgo.NewDecoder can be used to decode a given JWT:

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/alvii147/jwgo"
)

func main() {
	key := []byte("deadbeef")
	verifier := jwgo.NewHS256(key)

	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJwaW..."
	r := strings.NewReader(token)

	payload := jwgo.Payload{}
	err := jwgo.NewDecoder(r, verifier).Decode(&payload)
	if err != nil {
		fmt.Fprint(os.Stderr, "encoding failed", err)
	}

	fmt.Printf("%+v\n", payload)
	// {Issuer:pickle Subject:rick Audience:[foo] ExpirationTime:0x140000982f8 NotBefore:0x14000098300 IssuedAt:0x14000098308 JWTID:42}
}

Signing Methods

jwgo supports the following signing methods:

Method Name Method Details Constructor Function
HS256 HMAC + SHA-256 NewHS256
HS384 HMAC + SHA-384 NewHS384
HS512 HMAC + SHA-512 NewHS512
RS256 RSA-PKCS#1 v1.5 + SHA-256 NewRS256
RS384 RSA-PKCS#1 v1.5 + SHA-384 NewRS384
RS512 RSA-PKCS#1 v1.5 + SHA-512 NewRS512
PS256 RSA-PSS + SHA-256 NewPS256
PS384 RSA-PSS + SHA-384 NewPS384
PS512 RSA-PSS + SHA-512 NewPS512
ES256 ECDSA + SHA-256 NewES256
ES384 ECDSA + SHA-384 NewES384
ES512 ECDSA + SHA-512 NewES512
EdDSA Ed25519 NewEdDSA

Benchmark

The full results of benchmark can be found here. The following plots demonstrate the results of benchmarking the performance of HMAC-SHA256 JWT creation and parsing of jwgo against that of github.com/golang-jwt/jwt, which is the most popular Golang library for creating/parsing JWTs:

Runtime Benchmark Plot

Memory Benchmark Plot

Allocations Benchmark Plot

Documentation

Overview

Package jwgo is a Go library efficient generation and parsing of JSON web tokens.

Index

Constants

View Source
const (
	// ES256 represents ECDSA SHA-256 signing.
	ES256 = "ES256"
	// ES256Header is the pre-computed base64-encoded JWT header for ES256.
	ES256Header = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9"
	// ES256Size is key size for ES256.
	ES256Size = 32
	// ES384 represents ECDSA SHA-384 signing.
	ES384 = "ES384"
	// ES384Header is the pre-computed base64-encoded JWT header for ES384.
	ES384Header = "eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9"
	// ES384Size is key size for ES384.
	ES384Size = 48
	// ES512 represents ECDSA SHA-512 signing.
	ES512 = "ES512"
	// ES512Header is the pre-computed base64-encoded JWT header for ES512.
	ES512Header = "eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9"
	// ES512Size is key size for ES512.
	ES512Size = 66
)
View Source
const (
	// EdDSA represents Ed25519 signing.
	EdDSA = "EdDSA"
	// EdDSAHeader is the pre-computed base64-encoded JWT header for Ed25519.
	EdDSAHeader = "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9"
)
View Source
const (
	// HS256 represents HMAC SHA-256 signing.
	HS256 = "HS256"
	// HS256Header is the pre-computed base64-encoded JWT header for HMAC SHA-256.
	HS256Header = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
	// HS384 represents HMAC SHA-384 signing.
	HS384 = "HS384"
	// HS384Header is the pre-computed base64-encoded JWT header for HMAC SHA-384.
	HS384Header = "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9"
	// HS512 represents HMAC SHA-512 signing.
	HS512 = "HS512"
	// HS512Header is the pre-computed base64-encoded JWT header for HMAC SHA-512.
	HS512Header = "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9"
)
View Source
const (
	// PS256 represents RSA-PSS SHA-256 signing.
	PS256 = "PS256"
	// PS256Header is the pre-computed base64-encoded JWT header for PS256.
	PS256Header = "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9"
	// PS384 represents RSA-PSS SHA-384 signing.
	PS384 = "PS384"
	// PS384Header is the pre-computed base64-encoded JWT header for PS384.
	PS384Header = "eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9"
	// PS512 represents RSA-PSS SHA-512 signing.
	PS512 = "PS512"
	// PS512Header is the pre-computed base64-encoded JWT header for PS512.
	PS512Header = "eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9"
)
View Source
const (
	// RS256 represents RSA-PKCS#1 v1.5 SHA-256 signing.
	RS256 = "RS256"
	// RS256Header is the pre-computed base64-encoded JWT header for RS256.
	RS256Header = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"
	// RS384 represents RSA-PKCS#1 v1.5 SHA-384 signing.
	RS384 = "RS384"
	// RS384Header is the pre-computed base64-encoded JWT header for RS384.
	RS384Header = "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9"
	// RS512 represents RSA-PKCS#1 v1.5 SHA-512 signing.
	RS512 = "RS512"
	// RS512Header is the pre-computed base64-encoded JWT header for RS512.
	RS512Header = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9"
)
View Source
const (
	// Separator is the character separating different sections on the JWT.
	Separator string = "."
)

Variables

View Source
var (
	// ErrInvalidToken indicates token parsing errors.
	ErrInvalidToken = errors.New("invalid token")
	// ErrUnsupportedAlgorithm indicates the algorithm on the token's header is unsupported.
	ErrUnsupportedAlgorithm = errors.New("unsupported algorithm")
	// ErrInvalidSignature indicates a verification error in the token's signature.
	ErrInvalidSignature = errors.New("invalid signature")
	// ErrExpired indicates that the token is expired.
	ErrExpired = errors.New("expired")
	// ErrNotYetEffectiveToken indicates that the token is not yet effective.
	ErrNotYetEffectiveToken = errors.New("not yet effective")
	// ErrInvalidIssuedAt indicates that the token has an invalid issued at time.
	ErrInvalidIssuedAt = errors.New("invalid issued at")
)
View Source
var (
	// PSSSignOptions represents options for RSA-PSS signing.
	PSSSignOptions = &rsa.PSSOptions{
		SaltLength: rsa.PSSSaltLengthEqualsHash,
	}
	// PSSVerifyOptions represents options for RSA-PSS verification.
	PSSVerifyOptions = &rsa.PSSOptions{
		SaltLength: rsa.PSSSaltLengthAuto,
	}
)

Functions

func NewDecoder

func NewDecoder(r io.Reader, verifier Verifier) *decoder

NewDecoder creates and returns a new [decoder].

func NewEncoder

func NewEncoder(w io.Writer, signer Signer) *encoder

NewEncoder creates and returns a new [encoder].

Types

type ECDSA

type ECDSA struct {
	// contains filtered or unexported fields
}

ECDSA signs and verifies JWT using ECDSA signing.

func NewES256

func NewES256(publicKey *ecdsa.PublicKey, privateKey *ecdsa.PrivateKey) *ECDSA

NewES256 creates and returns a new ECDSA with ECDSA SHA-256 signing..

func NewES384

func NewES384(publicKey *ecdsa.PublicKey, privateKey *ecdsa.PrivateKey) *ECDSA

NewES384 creates and returns a new ECDSA with ECDSA SHA-384 signing..

func NewES512

func NewES512(publicKey *ecdsa.PublicKey, privateKey *ecdsa.PrivateKey) *ECDSA

NewES512 creates and returns a new ECDSA with ECDSA SHA-512 signing..

func (*ECDSA) Grow

func (e *ECDSA) Grow(n int)

Grow grows the allocated size of the underlying data.

func (*ECDSA) Header

func (e *ECDSA) Header() string

Header returns the pre-computed base64-encoded header.

func (*ECDSA) Sign

func (e *ECDSA) Sign() ([]byte, error)

Sign signs the written data.

func (*ECDSA) String

func (e *ECDSA) String() string

String returns the name of the algorithm.

func (*ECDSA) Verify

func (e *ECDSA) Verify(signature []byte) bool

Verify verifies the written data's signature against a given signature.

func (*ECDSA) Write

func (e *ECDSA) Write(p []byte) (int, error)

Write writes data for signing.

type ED25519

type ED25519 struct {
	// contains filtered or unexported fields
}

ED25519 signs and verifies JWT using Ed25519 signing.

func NewEdDSA

func NewEdDSA(publicKey ed25519.PublicKey, privateKey ed25519.PrivateKey) *ED25519

NewEdDSA creates and returns a new ED25519.

func (*ED25519) Grow

func (e *ED25519) Grow(n int)

Grow grows the allocated size of the underlying data.

func (*ED25519) Header

func (e *ED25519) Header() string

Header returns the pre-computed base64-encoded header.

func (*ED25519) Sign

func (e *ED25519) Sign() ([]byte, error)

Sign signs the written data.

func (*ED25519) String

func (e *ED25519) String() string

String returns the name of the algorithm.

func (*ED25519) Verify

func (e *ED25519) Verify(signature []byte) bool

Verify verifies the written data's signature against a given signature.

func (*ED25519) Write

func (e *ED25519) Write(p []byte) (int, error)

Write writes data for signing.

type HMAC

type HMAC struct {
	// contains filtered or unexported fields
}

HMAC signs and verifies JWT using HMAC SHA signing.

func NewHS256

func NewHS256(key []byte) *HMAC

NewHS256 creates and returns a new HMAC with HMAC SHA-256 signing.

func NewHS384

func NewHS384(key []byte) *HMAC

NewHS384 creates and returns a new HMAC with HMAC SHA-384 signing.

func NewHS512

func NewHS512(key []byte) *HMAC

NewHS512 creates and returns a new HMAC with HMAC SHA-512 signing.

func (*HMAC) Grow

func (h *HMAC) Grow(n int)

Grow grows the allocated size of the underlying data.

func (*HMAC) Header

func (h *HMAC) Header() string

Header returns the pre-computed base64-encoded header.

func (*HMAC) Sign

func (h *HMAC) Sign() ([]byte, error)

Sign signs the written data.

func (*HMAC) String

func (h *HMAC) String() string

String returns the name of the algorithm.

func (*HMAC) Verify

func (h *HMAC) Verify(signature []byte) bool

Verify verifies the written data's signature against a given signature.

func (*HMAC) Write

func (h *HMAC) Write(p []byte) (int, error)

Write writes data for signing.

type Header struct {
	// Algorithm is the signing algorithm used to sign the JWT.
	Algorithm string `json:"alg"`
	// Type represents the media type, which is always "JWT" in this case.
	Type string `json:"typ"`
}

Header represents the cryptographic operations applied to the JWT.

type Payload

type Payload struct {
	// Issuer identifies the principal that issued the JWT.
	Issuer string `json:"iss,omitempty"`
	// Subject identifies the principal that is the subject of the JWT.
	Subject string `json:"sub,omitempty"`
	// Audience identifies the recipients that the JWT is intended for.
	Audience []string `json:"aud,omitempty"`
	// ExpirationTime identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.
	ExpirationTime *int64 `json:"exp,omitempty"`
	// NotBefore identifies the time before which the JWT MUST NOT be accepted for processing.
	NotBefore *int64 `json:"nbf,omitempty"`
	// IssuedAt identifies the time at which the JWT was issued.
	IssuedAt *int64 `json:"iat,omitempty"`
	// JWTID provides a unique identifier for the JWT.
	JWTID string `json:"jti,omitempty"`
}

Payload represents registered claims conveyed by the JWT.

func (*Payload) GetTimes

func (p *Payload) GetTimes() (*int64, *int64, *int64)

GetTimes gets the expiration, not before, and issued at times of a Payload.

type RSAPKCS1v15

type RSAPKCS1v15 struct {
	// contains filtered or unexported fields
}

RSAPKCS1v15 signs and verifies JWT using RSA-PKCS#1 v1.5 signing.

func NewRS256

func NewRS256(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) *RSAPKCS1v15

NewRS256 creates and returns a new RSAPKCS1v15 with RSA-PKCS#1 v1.5 SHA-256 signing.

func NewRS384

func NewRS384(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) *RSAPKCS1v15

NewRS384 creates and returns a new RSAPKCS1v15 with RSA-PKCS#1 v1.5 SHA-384 signing.

func NewRS512

func NewRS512(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) *RSAPKCS1v15

NewRS512 creates and returns a new RSAPKCS1v15 with RSA-PKCS#1 v1.5 SHA-512 signing.

func (*RSAPKCS1v15) Grow

func (r *RSAPKCS1v15) Grow(n int)

Grow grows the allocated size of the underlying data.

func (*RSAPKCS1v15) Header

func (r *RSAPKCS1v15) Header() string

Header returns the pre-computed base64-encoded header.

func (*RSAPKCS1v15) Sign

func (r *RSAPKCS1v15) Sign() ([]byte, error)

Sign signs the written data.

func (*RSAPKCS1v15) String

func (r *RSAPKCS1v15) String() string

String returns the name of the algorithm.

func (*RSAPKCS1v15) Verify

func (r *RSAPKCS1v15) Verify(signature []byte) bool

Verify verifies the written data.

func (*RSAPKCS1v15) Write

func (r *RSAPKCS1v15) Write(p []byte) (int, error)

Write writes data for signing.

type RSAPSS

type RSAPSS struct {
	// contains filtered or unexported fields
}

RSAPSS signs and verifies JWT using RSA-PSS signing.

func NewPS256

func NewPS256(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) *RSAPSS

NewPS256 creates and returns a new RSAPSS with RSA-PSS SHA-256 signing.

func NewPS384

func NewPS384(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) *RSAPSS

NewPS384 creates and returns a new RSAPSS with RSA-PSS SHA-384 signing.

func NewPS512

func NewPS512(publicKey *rsa.PublicKey, privateKey *rsa.PrivateKey) *RSAPSS

NewPS512 creates and returns a new RSAPSS with RSA-PSS SHA-512 signing.

func (*RSAPSS) Grow

func (rp *RSAPSS) Grow(n int)

Grow grows the allocated size of the underlying data.

func (*RSAPSS) Header

func (rp *RSAPSS) Header() string

Header returns the pre-computed base64-encoded header.

func (*RSAPSS) Sign

func (rp *RSAPSS) Sign() ([]byte, error)

Sign signs the written data.

func (*RSAPSS) String

func (rp *RSAPSS) String() string

String returns the name of the algorithm.

func (*RSAPSS) Verify

func (rp *RSAPSS) Verify(signature []byte) bool

Verify verifies the written data.

func (*RSAPSS) Write

func (rp *RSAPSS) Write(p []byte) (int, error)

Write writes data for signing.

type Signer

type Signer interface {
	fmt.Stringer
	io.Writer
	Grow(n int)
	Header() string
	Sign() ([]byte, error)
}

Signer represents a signing algorithm.

type TimeConstrainedPayload

type TimeConstrainedPayload interface {
	GetTimes() (*int64, *int64, *int64)
}

TimeConstrainedPayload represents payloads with timed constraints.

type Verifier

type Verifier interface {
	fmt.Stringer
	io.Writer
	Grow(n int)
	Verify([]byte) bool
}

Verifier represents a signature verification algorithm.

Jump to

Keyboard shortcuts

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