keyphrase

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 8 Imported by: 0

README

keyphrase

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

keyphrase generates cryptographically random passwords, EFF-list passphrases, and BIP-39 mnemonics for Go. Selection is unbiased, policies are validated before generation, entropy is derived from the exact output distribution, and randomness is injectable through a context-aware interface.

This module does not hash passwords, implement wallets, derive BIP-32/BIP-44 keys, store secrets, or distribute credentials. Use password for password hashing and a purpose-built secret manager for storage and distribution.

Install

go get github.com/faustbrian/go-keyphrase/v2

The module requires Go 1.27.0 or later.

Status and portability

The v2 module follows the published compatibility and deprecation policies. Its public packages are portable Go: they have no platform-specific source files and require no operating-system service or external runtime backend. That portability statement does not imply validation on every GOOS and GOARCH combination.

Lifecycle, ownership, and concurrency

Selectors and generators are stateless after construction. The default variants use crypto/rand and may be shared across goroutines. A selector created with a custom randomness source may be shared only when that source supports concurrent ReadContext calls. Callers must not mutate policy slices, custom sources, or destination buffers while an operation is using them.

Contexts, injected randomness sources, policy inputs, and destination buffers remain caller-owned. Validated word lists copy their input and expose immutable lookups; methods that return words, entropy, or generated secrets return caller-owned copies. Generation into a caller buffer occurs only after the complete secret has been produced successfully.

The module starts no goroutines, performs no background work, and owns no files, sockets, services, or other runtime resources. Selectors, generators, lists, and generated values have no Close or Shutdown lifecycle. Callers control cancellation and the lifetime and best-effort clearing of returned secret bytes. See performance and operational limits for cost and cancellation caveats.

Password quick start

policy := password.Policy{
    Length:   20,
    Alphabet: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    Required: []password.Class{
        {Name: "lower", Characters: "abcdefghijklmnopqrstuvwxyz"},
        {Name: "upper", Characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
        {Name: "digit", Characters: "0123456789"},
    },
    MinimumEntropyBits: 100,
}
secret, err := password.DefaultGenerator().Generate(ctx, policy)
if err != nil { /* handle without logging the secret */ }
defer clear(secret)

Required classes are sampled from the complete valid output space. The generator does not force classes into fixed positions and does not repair an initial password with a biased shuffle.

Passphrase quick start

list, err := eff.Large()
if err != nil { /* embedded-list integrity failure */ }
phrase, err := passphrase.DefaultGenerator().Generate(ctx, passphrase.Policy{
    WordList:  list,
    Words:     6,
    Separator: " ",
})
defer clear(phrase)

The package embeds both EFF short lists and the 7,776-word long list with pinned source and transformed-content checksums.

BIP-39 quick start

mnemonic, err := bip39.Generate(
    ctx, 256, bip39.English, keyphrase.DefaultSelector(),
)
seed, err := bip39.Seed(ctx, mnemonic, passphrase)
defer clear(seed)

All ten official word lists, every official entropy size, NFKD normalization, checksum validation, ambiguity-aware language detection, and the specified PBKDF2-HMAC-SHA512 derivation are supported. BIP-39 seed derivation is included for interoperability; wallet behavior is intentionally absent.

Moving from v1 to v2 changes every Go import to github.com/faustbrian/go-keyphrase/v2[/package]. bip39.Seed now uses the maintained Go PBKDF2 primitive. It checks cancellation before and after the fixed derivation rather than during its rounds; an in-progress call cannot be preempted by its context. See the BIP-39 guide for the strict FIPS-mode limitation.

The checked-in Example_passphrase is the executable five-minute example. It is compiled and run by the Go example test gate.

Security status

The repository runs official vectors, independent interoperability fixtures, property tests, statistical smoke tests, fuzz targets, race tests, mutation tests, and embedded-list integrity checks. An independent agent cryptographic design review approved the v2 source at 4185b83263be3b13aa26ff0ec84c8dfd5d16c174; this is not a human third-party certification. The review record describes its scope and residual risks. Release still requires the applicable CI and release gates.

Generated byte slices can be cleared as a best-effort measure. Go strings, compiler copies, runtime copies, crash dumps, swap, and downstream copies make complete erasure impossible. See secret lifetime.

Documentation

Use the documentation index for the complete guide set. Start with adoption, the API map, and the executable example. Operational and project navigation is available through troubleshooting, the FAQ, support, security reporting, the changelog, and the license.

For ecosystem-wide construction, ownership, lifecycle, and composition guidance, see the versioned Golib ecosystem index and its Domain utilities family.

License

Project code and BIP-39 material are MIT licensed. EFF-derived list data is used under CC BY 3.0 US. See THIRD_PARTY_NOTICES.md.

Documentation

Overview

Package keyphrase provides shared cryptographic randomness and entropy contracts for password, passphrase, and BIP-39 mnemonic generation.

It does not hash passwords, manage wallets, derive wallet keys, store secrets, or distribute secret material.

Example (Passphrase)
package main

import (
	"context"
	"fmt"

	"github.com/faustbrian/go-keyphrase/v2/passphrase"
	"github.com/faustbrian/go-keyphrase/v2/wordlist/eff"
)

func main() {
	list, err := eff.Large()
	if err != nil {
		panic(err)
	}
	secret, err := passphrase.DefaultGenerator().Generate(context.Background(), passphrase.Policy{
		WordList:  list,
		Words:     6,
		Separator: " ",
	})
	if err != nil {
		panic(err)
	}
	defer clear(secret)

	fmt.Println(len(secret) > 0)
}
Output:
true

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error struct {
	Code  ErrorCode
	Cause error
}

Error is a typed, secret-safe generation error.

Error deliberately omits the wrapped error text. Callers that need the underlying cause may inspect it with errors.Is or errors.As, but should not log arbitrary source errors without reviewing their disclosure behavior.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Format

func (e *Error) Format(state fmt.State, _ rune)

Format prevents wrapped source diagnostics from appearing in debug output.

func (*Error) MarshalText

func (e *Error) MarshalText() ([]byte, error)

MarshalText omits wrapped source diagnostics from encoded output.

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorCode

type ErrorCode string

ErrorCode identifies a generation failure without exposing secret material.

const (
	// CodeInvalidBound reports a nonpositive selection bound.
	CodeInvalidBound ErrorCode = "invalid_bound"
	// CodeInvalidSource reports a nil randomness source.
	CodeInvalidSource ErrorCode = "invalid_source"
	// CodeInvalidOption reports an invalid selector option.
	CodeInvalidOption ErrorCode = "invalid_option"
	// CodeOversized reports a request above a resource limit.
	CodeOversized ErrorCode = "oversized"
	// CodeSource reports a randomness-source failure.
	CodeSource ErrorCode = "source_failure"
	// CodeShortRead reports a source that made invalid progress.
	CodeShortRead ErrorCode = "short_read"
	// CodeAttemptsExceeded reports too many rejected samples.
	CodeAttemptsExceeded ErrorCode = "attempts_exceeded"
	// CodeCanceled reports context cancellation.
	CodeCanceled ErrorCode = "canceled"
)

type Option

type Option func(*Selector) error

Option configures a Selector.

func WithMaxAttempts

func WithMaxAttempts(maxAttempts int) Option

WithMaxAttempts bounds rejected samples from a faulty or hostile source.

type Secret

type Secret []byte

Secret is a caller-owned byte slice whose fmt representation is always redacted. Convert it explicitly to []byte or string only at a reviewed integration boundary.

func (Secret) Clear

func (s Secret) Clear()

Clear overwrites the current backing array as a best-effort measure. Go and the operating system may retain compiler, runtime, string, or page copies.

func (Secret) Format

func (Secret) Format(state fmt.State, _ rune)

Format prevents accidental disclosure through logging and debugging verbs.

func (Secret) LogValue

func (Secret) LogValue() slog.Value

LogValue prevents disclosure through the standard structured logger.

func (Secret) MarshalText

func (Secret) MarshalText() ([]byte, error)

MarshalText prevents disclosure through standard text and JSON encoders.

type Selector

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

Selector performs bounded rejection sampling from a Source.

func DefaultSelector

func DefaultSelector() *Selector

DefaultSelector returns a selector backed by crypto/rand.

func NewSelector

func NewSelector(source Source, options ...Option) (*Selector, error)

NewSelector constructs a selector using source.

func (*Selector) BigInt

func (s *Selector) BigInt(ctx context.Context, upper *big.Int) (*big.Int, error)

BigInt returns a uniformly distributed arbitrary-precision value in [0, upper). The returned integer never aliases upper.

func (*Selector) Fill

func (s *Selector) Fill(ctx context.Context, destination []byte) error

Fill writes cryptographic random bytes into destination. On failure it clears destination so callers never observe a partial secret.

func (*Selector) Index

func (s *Selector) Index(ctx context.Context, upper uint64) (uint64, error)

Index returns a uniformly distributed value in [0, upper).

type Source

type Source interface {
	ReadContext(ctx context.Context, destination []byte) (int, error)
}

Source supplies cryptographic random bytes and participates in cancellation. Implementations must fill as much of destination as possible and must return promptly after ctx is canceled.

Directories

Path Synopsis
Package bip39 implements BIP-39 mnemonic encoding, validation, language detection, and seed derivation.
Package bip39 implements BIP-39 mnemonic encoding, validation, language detection, and seed derivation.
Package keyphrasetest provides deterministic sources and statistical test helpers.
Package keyphrasetest provides deterministic sources and statistical test helpers.
Package passphrase generates and validates uniformly selected word-list passphrases with optional independently generated password affixes.
Package passphrase generates and validates uniformly selected word-list passphrases with optional independently generated password affixes.
Package password generates uniformly distributed passwords under explicit character and required-class policies.
Package password generates uniformly distributed passwords under explicit character and required-class policies.
Package wordlist validates and exposes immutable cryptographic word lists.
Package wordlist validates and exposes immutable cryptographic word lists.
eff
Package eff embeds the Electronic Frontier Foundation diceware word lists with pinned source and integrity metadata.
Package eff embeds the Electronic Frontier Foundation diceware word lists with pinned source and integrity metadata.

Jump to

Keyboard shortcuts

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