crypto

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MinKeyLength is the minimum required length for JWT signing keys.
	// 32 bytes (256 bits) is the minimum recommended length for HMAC-SHA256 keys
	// to provide sufficient security against brute force attacks.
	MinKeyLength = 32

	// JWT claim constants
	ClaimIssuedAt  = "iat"     // JWT Issued At claim key
	ClaimExpiresAt = "exp"     // JWT Expiration Time claim key
	ClaimUserID    = "user_id" // JWT User ID claim key

	// Email verification specific claims
	ClaimEmail              = "email"          // Email address being verified
	ClaimType               = "type"           // Verification type claim
	ClaimVerificationValue  = "verification"   // Value for verification type claim
	ClaimPasswordResetValue = "password_reset" // Value for password reset type claim
	ClaimEmailChangeValue   = "email_change"   // Value for email change type claim
	ClaimNewEmail           = "new_email"      // New email address for email change claims

	// MaxTokenAge is the maximum age a JWT token can be before it's considered too old (7 days in seconds)
	MaxTokenAge = 7 * 24 * 60 * 60
)
View Source
const AlphanumericAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
View Source
const Oauth2StateLength = 32

The OAuth2 specification (RFC 6749) doesn’t mandate a specific length. It recommends a random, unguessable string. At least 16 characters, though 32 to 64 characters is common for better uniqueness and security.

View Source
const OauthCodeVerifierLength = 43

Defined in RFC 7636 (PKCE). Its length must be between 43 and 128 characters.

View Source
const PKCECodeChallengeMethod = "S256"

PKCE code challenge method as defined in RFC 7636

Variables

View Source
var (

	// ErrJwtTokenExpired is returned when the token has expired
	ErrJwtTokenExpired = errors.New("token expired")
	// ErrJwtInvalidToken is returned when the token is invalid
	ErrJwtInvalidToken = errors.New("invalid token")
	// ErrInvalidVerificationToken is returned when verification token is invalid
	ErrInvalidVerificationToken = errors.New("invalid verification token")
	// ErrJwtInvalidSigningMethod is returned when the signing method is not HS256
	ErrJwtInvalidSigningMethod = errors.New("unexpected signing method")
	// ErrJwtInvalidSecretLength is returned for invalid secret lengths
	ErrJwtInvalidSecretLength = errors.New("invalid secret length")
	// ErrInvalidSigningKeyParts is returned when email or password hash are empty
	ErrInvalidSigningKeyParts = errors.New("invalid signing key parts")
	// ErrTokenUsedBeforeIssued is returned when a token's "iat" (issued at) claim
	// is in the future, indicating the token is being used before it was issued
	ErrTokenUsedBeforeIssued = errors.New("token used before issued")
	// ErrInvalidClaimFormat is returned when a claim has the wrong type
	ErrInvalidClaimFormat = errors.New("invalid claim format")
	// ErrClaimNotFound is returned when a required claim is missing
	ErrClaimNotFound = errors.New("claim not found")
	// ErrTokenTooOld is returned when a token's "iat" (issued at) claim
	// is older than the maximum allowed age (one week)
	ErrTokenTooOld = errors.New("token too old")
)

Functions

func CheckPassword

func CheckPassword(password, hash string) bool

CheckPassword compares a bcrypt hashed password with its possible plaintext equivalent

func GenerateHash

func GenerateHash(password string) (string, error)

GenerateHash creates a bcrypt hash from a password using reasonable default cost

func NewJwt

func NewJwt(payload jwt.MapClaims, signingKey []byte, duration time.Duration) (string, error)

func NewJwtEmailChangeToken

func NewJwtEmailChangeToken(userID, oldEmail, newEmail, passwordHash, secret string, duration time.Duration) (string, error)

NewJwtPasswordResetToken creates a JWT specifically for password reset

func NewJwtEmailVerificationToken

func NewJwtEmailVerificationToken(userID, email, passwordHash, secret string, duration time.Duration) (string, error)

NewJwtEmailVerificationToken creates a JWT specifically for email verification It includes additional claims needed for verification

func NewJwtPasswordResetToken

func NewJwtPasswordResetToken(userID, email, passwordHash, secret string, duration time.Duration) (string, error)

func NewJwtSessionToken

func NewJwtSessionToken(userID, email, passwordHash, secret string, duration time.Duration) (string, error)

NewJwtSession creates a new JWT session token for a user It handles the complete token generation process including: - Creating the signing key from user credentials - Setting up standard claims - Generating and signing the token

func NewJwtSigningKeyWithCredentials

func NewJwtSigningKeyWithCredentials(email, passwordHash, secret string) ([]byte, error)

It derives a unique key by combining user-specific data (email, passwordHash) with a server secret (JWT_SECRET). Tokens are invalidated when the user's email or password changes, or globally by rotating JWT_SECRET.

The passwordHash parameter can be empty to support passwordless authentication methods like OAuth2. In this case, the signing key is derived only from the email and server secret.

Using HMAC prevents length-extension attacks, unlike simple hash concatenation.

The function uses a null byte (\x00) as a delimiter to prevent collisions between the email and passwordHash inputs. It returns the key as a byte slice, suitable for use with github.com/golang-jwt/jwt/v5's SignedString method, and an error if the server secret is unset or inputs are invalid.

Note: JWT_SECRET should be a strong, random value (e.g., 32+ bytes).

func Oauth2CodeVerifier

func Oauth2CodeVerifier() string

func Oauth2State

func Oauth2State() string

The state parameter helps prevent Cross-Site Request Forgery (CSRF) attacks by linking the authorization request to its callback. Should be URL-safe, Here alphanumeric characters.

func ParseJwt

func ParseJwt(token string, verificationKey []byte) (jwt.MapClaims, error)

ParseJwt verifies and parses JWT and returns its claims. returns a map map[string]any that you can access like any other Go map.

exp := claims["exp"].(float64)

func ParseJwtUnverified

func ParseJwtUnverified(tokenString string) (jwt.MapClaims, error)

Implement only the validation rather than using the full validator but this is not lightweight either, 60% so expensive as full.

func RandomString

func RandomString(length int, alphabet string) string

func S256Challenge

func S256Challenge(code string) string

S256Challenge creates base64 encoded sha256 challenge string derived from code. The padding of the result base64 string is stripped per RFC 7636.

func ValidateEmailChangeClaims

func ValidateEmailChangeClaims(claims jwt.MapClaims) error

func ValidateEmailVerificationClaims

func ValidateEmailVerificationClaims(claims jwt.MapClaims) error

func ValidatePasswordResetClaims

func ValidatePasswordResetClaims(claims jwt.MapClaims) error

func ValidateSessionClaims

func ValidateSessionClaims(claims jwt.MapClaims) error

Types

This section is empty.

Jump to

Keyboard shortcuts

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