crypto

package
v0.8.2 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package crypto provides a small, opinionated set of cryptographic primitives for building authentication systems. It deliberately exposes a narrow surface so callers cannot reach for a weaker construction:

  • RandomBytes / RandomToken / RandomTokenHex mint cryptographically-secure opaque tokens (session tokens, magic-link tokens, nonces). The default TokenBytes is 32 (256 bits of entropy).
  • HMACSHA256 / HMACHex / HMACEqual are the keyed hash used for HIGH-entropy secrets (for example API keys) and for integrity tags. HMAC gives O(1), constant-length, direct-lookup validation with a constant-time compare — no per-request password-hashing cost on a hot path.
  • SHA256Hex derives non-reversible keys from opaque tokens so a raw token is never used as (or recoverable from) a cache key.
  • HashPassword / VerifyPassword implement argon2id, reserved strictly for LOW-entropy secrets (human passphrases, recovery codes). It is never used to validate high-entropy keys.

Every comparison in this package is constant time; malformed inputs compare as not-equal or return an error rather than panicking.

Index

Constants

View Source
const TokenBytes = 32

TokenBytes is the default entropy, in bytes, of a generated opaque token. 32 bytes is 256 bits, a common strength for session and magic-link tokens.

Variables

View Source
var (
	// ErrInvalidTokenLength is returned when a non-positive byte length is
	// requested from a token generator.
	ErrInvalidTokenLength = errors.New("crypto: token length must be positive")

	// ErrInvalidPasswordHash is returned when an encoded argon2id string cannot be
	// parsed (wrong shape, bad base64, or out-of-range parameters).
	ErrInvalidPasswordHash = errors.New("crypto: malformed argon2id hash")

	// ErrIncompatiblePasswordHash is returned when an encoded argon2id string
	// declares an argon2 version this build cannot verify.
	ErrIncompatiblePasswordHash = errors.New("crypto: incompatible argon2id version")
)

Static error variables for err113 compliance.

Functions

func ConstantTimeEqual

func ConstantTimeEqual(a, b string) bool

ConstantTimeEqual reports whether a and b are equal in constant time. Use it to compare fixed-length opaque values (nonces, state tokens) where timing must not leak how much of a mismatch occurred.

func HMACEqual

func HMACEqual(a, b string) bool

HMACEqual reports whether two hex-encoded HMAC tags are equal in constant time. A malformed hex input compares as not-equal and never panics, so it is safe to feed attacker-controlled values directly.

func HMACHex

func HMACHex(pepper []byte, message string) string

HMACHex returns the lowercase hex HMAC-SHA256 of message under pepper. This is the keyed hash used for high-entropy secrets (for example API keys) and for integrity tags: it is O(1) to compute, constant length, and enables direct-lookup validation without a per-request password-hash cost.

func HMACSHA256

func HMACSHA256(key, message []byte) []byte

HMACSHA256 returns the raw HMAC-SHA256 of message under key.

func HashPassword

func HashPassword(secret string) (string, error)

HashPassword hashes secret with argon2id using DefaultArgon2Params and a fresh random salt, returning a self-describing PHC-format string ($argon2id$v=19$m=,t=,p=$salt$hash) that VerifyPassword can parse.

func HashPasswordWithParams

func HashPasswordWithParams(secret string, p Argon2Params) (string, error)

HashPasswordWithParams is HashPassword with caller-supplied cost parameters. It is exported so operators can tune cost per environment (and so tests can use cheap parameters).

func RandomBytes

func RandomBytes(n int) ([]byte, error)

RandomBytes returns n cryptographically-secure random bytes. It returns ErrInvalidTokenLength for a non-positive n, and wraps any CSPRNG failure (which callers should treat as fatal — never fall back to a weaker source).

func RandomToken

func RandomToken(n int) (string, error)

RandomToken returns a URL-safe, unpadded base64 token carrying n bytes of entropy. With n == TokenBytes the result is a 256-bit opaque token suitable for session cookies, magic-link tokens, and access tokens.

func RandomTokenHex

func RandomTokenHex(n int) (string, error)

RandomTokenHex returns a lowercase hex token carrying n bytes of entropy. Hex is used where a value must be case-insensitive or embedded in a context that mangles URL-safe base64.

func SHA256Hex

func SHA256Hex(s string) string

SHA256Hex returns the lowercase hex SHA-256 of s. It is used to derive cache keys from opaque tokens (for example session:<sha256(token)>) so a raw token is never used as, or recoverable from, a cache key. SHA-256 here is a key derivation, not a credential comparison — never compare secrets by their SHA-256 without HMAC.

func VerifyPassword

func VerifyPassword(secret, encoded string) (bool, error)

VerifyPassword reports whether secret matches an encoded argon2id hash from HashPassword. The final comparison is constant time. A malformed or unsupported encoded value returns an error and never a false positive.

Types

type Argon2Params

type Argon2Params struct {
	// Memory is the memory cost in KiB.
	Memory uint32
	// Iterations is the time cost (number of passes).
	Iterations uint32
	// Parallelism is the number of lanes.
	Parallelism uint8
	// SaltLength is the salt size in bytes used when hashing.
	SaltLength uint32
	// KeyLength is the derived-key size in bytes.
	KeyLength uint32
}

Argon2Params configures argon2id password hashing.

func DefaultArgon2Params

func DefaultArgon2Params() Argon2Params

DefaultArgon2Params returns argon2id parameters tuned per current OWASP guidance (19 MiB memory, 2 iterations, 1 lane). argon2id is reserved for LOW-entropy secrets (human passphrases, recovery codes); high-entropy keys use HMACHex instead and never pay this cost on a hot path.

Jump to

Keyboard shortcuts

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