Documentation
¶
Overview ¶
Package hash defines the password-hashing contract and a Hasher facade that hashes and checks values and reports hashes that need rehashing. Exact string and []byte values use raw password bytes. Other types, including named string and slice types, use JSON; hash and check with the same encoding, or explicitly convert named values when raw-byte behavior is required.
Optional aggregate metrics count and time complete facade calls, including encoding failures. No spans or events are created. Nil Builder.Telemetry follows telemetry.Default per call; telemetry.New(nil) disables reporting. Disabled calls do not read time or construct metric instruments. Labels use bounded operation, outcome and error classes, never values, hashes or native errors. Check mismatches are normal outcomes. NeedsRehash observations do not report persisted hash updates. Calls that panic in a driver or application JSON encoder propagate that panic unchanged and produce no completed count or duration observation.
Example:
hasher := hash.New(driver, func(hasher *hash.Builder) {
hasher.Telemetry(metrics)
})
stored, err := hasher.Hash("password")
if err != nil {
return err
}
_ = stored
Index ¶
- Variables
- type Builder
- type BuilderFunc
- type Driver
- type Hasher
- func (hasher *Hasher) Check[T any](value T, valueHash []byte) (match bool, err error)
- func (hasher *Hasher) CheckRaw(value, valueHash []byte) (match bool, err error)
- func (hasher *Hasher) Driver() Driver
- func (hasher *Hasher) DriverAs[T any]() (T, bool)
- func (hasher *Hasher) Hash[T any](value T) (result []byte, err error)
- func (hasher *Hasher) HashRaw(value []byte) (result []byte, err error)
- func (hasher *Hasher) NeedsRehash(valueHash []byte) (needed bool)
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidHash = errors.New("invalid hash")
ErrInvalidHash indicates that a stored hash is malformed or was not produced by the driver's algorithm. A password mismatch is not this error: Check and CheckRaw return false, nil for a well-formed nonmatching hash.
Example:
match, err := hasher.Check(password, stored)
if errors.Is(err, hash.ErrInvalidHash) {
return fmt.Errorf("stored password hash is malformed: %w", err)
}
if err != nil {
return err
}
_ = match
Functions ¶
This section is empty.
Types ¶
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder configures aggregate metrics at construction. New publishes an independent settings snapshot; the telemetry service itself remains shared.
Example:
hasher := hash.New(driver, func(hasher *hash.Builder) {
hasher.Telemetry(metrics)
})
_ = hasher
func (*Builder) Telemetry ¶
Telemetry selects aggregate metrics without traces or events. Nil resolves telemetry.Default per call; telemetry.New(nil) explicitly disables metrics. The service is shared, not copied. This method returns the same draft.
Example:
hasher := hash.New(driver, func(hasher *hash.Builder) {
hasher.Telemetry(telemetry.New(nil))
})
_ = hasher
type BuilderFunc ¶
type BuilderFunc = func(*Builder)
BuilderFunc configures one fresh draft directly, synchronously and once in order. Nil entries panic; expanded nil or empty slices supply no edits. New copies the service selection, not the service object, and does not retain construction callbacks or clone the state referenced by the driver.
Example:
var policy hash.BuilderFunc = func(hasher *hash.Builder) {
hasher.Telemetry(metrics)
}
hasher := hash.New(driver, policy)
_ = hasher
type Driver ¶
type Driver interface {
// Hash hashes raw bytes without modifying them. Empty input is valid; the
// returned hash includes a fresh salt, even for repeated equal inputs.
// Drivers return errors for unsupported inputs or hashing failures.
//
// Example:
//
// stored, err := driver.Hash([]byte("fixture password"))
// if err != nil {
// return err
// }
// _ = stored
Hash(value []byte) ([]byte, error)
// Check verifies raw bytes against a stored hash. A value that does not
// match yields (false, nil); a hash the driver cannot parse yields
// (false, err) with err wrapping [ErrInvalidHash].
//
// Example:
//
// match, err := driver.Check([]byte("fixture password"), stored)
// if err != nil {
// return err
// }
// _ = match // A false result rejects the password, not the stored hash format.
Check(value []byte, hash []byte) (bool, error)
// NeedsRehash reports whether the given hash was produced with different
// parameters than the current configuration, indicating the value should be
// re-hashed. A hash the driver cannot parse needs rehashing. The example's
// persistReplacement function is application-owned password-hash storage.
//
// Example:
//
// match, err := driver.Check(password, stored)
// if err != nil {
// return err
// }
// if match && driver.NeedsRehash(stored) {
// replacement, err := driver.Hash(password)
// if err != nil {
// return err
// }
// if err := persistReplacement(replacement); err != nil {
// return err
// }
// }
NeedsRehash(hash []byte) bool
}
Driver hashes and verifies raw values and checks whether stored hashes use stale parameters.
Implementations must not modify the value slice they are given: the caller may keep using it, for example to check a password and then rehash it with new parameters.
Hash accepts an empty value and embeds a fresh random salt, so hashing the same value twice yields different hashes that both pass Check.
Example:
var driver hash.Driver = hasher.Driver()
stored, err := driver.Hash([]byte("fixture password"))
if err != nil {
return err
}
_ = stored // Raw driver calls bypass facade encoding and metrics.
type Hasher ¶
type Hasher struct {
// contains filtered or unexported fields
}
Hasher provides typed hashing over a Driver, with optional aggregate metrics. It is immutable after New and safe for concurrent use when the driver is. Construct it with New; the zero Hasher has no driver for operations.
Example:
hasher := hash.New(driver)
stored, err := hasher.Hash("password")
if err != nil {
return err
}
_ = stored
func New ¶
func New(driver Driver, configure ...BuilderFunc) *Hasher
New creates a Hasher that delegates to driver. Construction callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and nil/empty expansions omit edits. Retained drafts cannot change published settings; the driver and telemetry service remain shared. Callbacks are not retained. New makes no driver calls and does not validate driver. An operation that reaches a nil Driver interface panics; the caller retains any driver-specific lifecycle.
Example:
hasher := hash.New(driver, func(hasher *hash.Builder) {
hasher.Telemetry(telemetry.New(nil))
})
_ = hasher
func (*Hasher) Check ¶
Check encodes value as Hasher.Hash does and verifies it against valueHash. Exact string and []byte values use raw bytes; named string and slice types use JSON. Converting between those forms can cause a password mismatch even when their underlying bytes look identical. Like Hash, Check zeroes only its own encoded copy, never value. Metrics include encoding failures; false, nil is a mismatch, not an error. A panic propagates without recording a completed operation or mismatch.
Example:
match, err := hasher.Check("attempt", stored)
if err != nil {
return err
}
_ = match
func (*Hasher) CheckRaw ¶
CheckRaw verifies raw bytes against valueHash. It does not modify value. Its metrics distinguish mismatch (false, nil) from malformed hashes or errors. A panic propagates without recording a completed operation or mismatch.
Example:
match, err := hasher.CheckRaw(password, stored)
if err != nil {
return err
}
_ = match
func (*Hasher) Driver ¶
Driver returns the shared underlying hashing driver, not a copy. Direct driver calls use raw bytes and bypass this Hasher's encoding, buffer clearing, and aggregate metrics. The caller still owns any driver-specific lifecycle.
Example:
stored, err := hasher.Driver().Hash([]byte("fixture password"))
if err != nil {
return err
}
_ = stored
func (*Hasher) DriverAs ¶
DriverAs returns the first driver of type T in the chain of the underlying driver. A driver that wraps another exposes it with an Unwrap() Driver method, so wrappers such as prefixing or tracing drivers do not hide the concrete driver. A failed match returns the zero T and false. Native calls on a matched driver bypass facade metrics.
With argon2hash imported from arkoren.dev/driver/argon2/argon2hash:
driver, ok := hasher.DriverAs[*argon2hash.Driver]()
if !ok {
return errors.New("hasher does not use Argon2")
}
needed := driver.NeedsRehash(stored)
_ = needed // Rehash only after a successful password check.
func (*Hasher) Hash ¶
Hash hashes value. Exact string and []byte values use their raw bytes, so Hash("secret") and HashRaw([]byte("secret")) use the same password bytes, although fresh salts make their stored hashes different. Other types, including named string or slice types, are JSON-encoded first. Check with the same encoding or explicitly convert a named value to string or []byte when raw-byte behavior is intended. bcrypt drivers reject inputs over 72 encoded bytes. Hash zeroes its own encoded copy after hashing, never value. Metrics cover returned encoding and hashing outcomes once, including errors. A panic propagates without recording a completed operation.
Example:
stored, err := hasher.Hash("password")
if err != nil {
return err
}
_ = stored
func (*Hasher) HashRaw ¶
HashRaw hashes raw bytes. It does not modify value, so the caller may reuse it, for example to rehash a password after a successful Hasher.CheckRaw. A normal return records one hash operation without encoding; panics propagate without recording a completed operation.
Example:
stored, err := hasher.HashRaw(password)
if err != nil {
return err
}
_ = stored
func (*Hasher) NeedsRehash ¶
NeedsRehash reports whether valueHash uses stale driver parameters. Its metrics report policy observations, never a completed password update. A panic propagates without recording a completed policy observation.
Example:
needed := hasher.NeedsRehash(stored) _ = needed // Rehash only after a successful password check.