https://github.com/decadenza/luhn
Luhn Mod N algorithm as a Go module
https://github.com/decadenza/luhn
checksum luhn-algorithm validation
Last synced: 3 months ago
JSON representation
Luhn Mod N algorithm as a Go module
- Host: GitHub
- URL: https://github.com/decadenza/luhn
- Owner: decadenza
- License: apache-2.0
- Created: 2024-05-13T19:07:36.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2024-05-15T13:59:33.000Z (about 1 year ago)
- Last Synced: 2025-01-17T23:43:35.277Z (5 months ago)
- Topics: checksum, luhn-algorithm, validation
- Language: Go
- Homepage:
- Size: 17.6 KB
- Stars: 0
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Luhn algorithm
Implementation of Luhn Mod N algorithm for *any base (modulus)* divisible by 2 in the range from 2 to 36.
Most used configurations are:
- Luhn Mod 10
- Luhn Mod 16 (hexadecimal)
- Luhn Mod 36 (all 0-9 and A-Z characters)## Character mapping
The character mapping is based on the standard [strconv](https://pkg.go.dev/strconv) package.
Letter `A` is mapped to 10 and all other letters are mapped subsequentially, up to letter `Z` which is mapped to 36.
The expected input is a string where each character is treated independently.## Pros and cons
The Luhn algorithm will detect all single-digit errors, as well as almost all transpositions of adjacent digits. It will not, however, detect transposition of the two-digit sequence _(base-1)_-0 to 0-_(base-1)_ (or vice versa), e.g. swapping 09 with 90 in Mod 10.
It will detect most of the possible twin errors, but not all of them (e.g. in Mod 10 it will not detect 22 ↔ 55, 33 ↔ 66 or 44 ↔ 77).## Install and import
Install with:
```
go get -u github.com/decadenza/luhn
```
Import as:
```
import "github.com/decadenza/luhn"
```## Basic example
```
package mainimport (
"fmt""github.com/decadenza/luhn"
)func main() {
base := 16
myPayload := "14FAD"luhn, err := luhn.New(base)
if err != nil {
panic(err)
}// Generate and concatenate checksum.
checksum, err := luhn.GetChecksum(myPayload)
if err != nil {
panic(err)
}
fullCode := myPayload + checksum// Check its validity.
valid := luhn.IsValid(fullCode)
fmt.Printf("%s is valid? %t\n", fullCode, valid)// A mistyping will not be valid.
wrongCode := "1AFAD" + checksum
valid = luhn.IsValid(wrongCode)
fmt.Printf("%s is valid? %t\n", wrongCode, valid)
}
```Refer to test files for further examples.
## References
- [Luhn algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm)
- [Luhn mod N algorithm](https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm)