keyphrase

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 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

The module requires Go 1.26.6 or later.

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.

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. A stable release remains blocked until an independent cryptographic design review is recorded in the review report. Tag builds enforce that record with make stable-release-check.

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

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.

Ecosystem

Use the Golib documentation portal to choose companion packages, supported stacks, recipes, and operations guidance.

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/passphrase"
	"github.com/faustbrian/go-keyphrase/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