Skip to content

blushft/luhner

Repository files navigation

Go Report Card Go go.dev reference MIT License

Contributors Forks


Luhner

Generate and verify identifiers algorithmically

About

Luhner (pronouced like lunar) is a go implementation of the Luhn mod N algorithm.

Important Notice

The Luhn algorithm is useful to validate identifiers but is not a secure cryptographic hash and should not be used to protect privieleged access or data.

Usage

Basic

The simplest usage of luhner are the built in Generate() and Validate() functions:

id, err := luhner.Generate()
if err != nil {
    log.Fatal(err)
}

valid := luhner.Validate(id)
log.Printf("ID valid = %t", valid)

The default functions can be adjusted using package options to set the Length, Prefix, or Charset. Any options passed to Generate() must also be passed to Validate():

id, err := luhner.Generate(luhner.Length(10))
if err != nil {
    log.Fatal(err)
}

valid := luhner.Validate(id, luhner.Length(10))

Instance

An Instance contains a generator and validator using a common config:

inst := luhner.NewInstance(luhner.Length(8), luhner.Prefix("XYZ"))

id, err := inst.Generate()
if err != nil {
    log.Fatal(err)
}

valid := inst.Validate(id)

Config Interface

Advanced use cases can leverage the Config interface to provide custom implementations:

type Config interface {
    Length() int
    Mod() int
    Charset() []string
    CodePoint(s string) (int, bool)
    Prefix(string) string
}

An example implementation for a custom keygen is supplied in the example folder.