a Unified HOTP & TOTP Package in Go
- Go 100%
| algorithm.go | ||
| go.mod | ||
| go.sum | ||
| hotp.go | ||
| main.go | ||
| README.md | ||
| totp.go | ||
| uri.go | ||
| util.go | ||
anar-otp - Unified HOTP & TOTP Package in Go
anar-otp is a comprehensive Go package for generating and verifying HOTP (HMAC-based One-Time Passwords) and TOTP (Time-based One-Time Passwords). It also supports QR code generation for provisioning URIs.
Features
- Supports HOTP and TOTP.
- Configurable digits, hashing algorithms (SHA1, SHA256, SHA512), periods, and skew.
- Automatic secret generation per algorithm.
- QR code generation (PNG and Base64) for easy provisioning.
- Convenient unified OTP struct for easy handling.
- Verification with optional window or skew.
Installation
go get codeberg.org/anarproject/anar-otp
Usage
Generate a secret
package main
import (
"fmt"
"codeberg.org/anarproject/anar-otp"
)
func main() {
secret, err := anar_otp.GenerateSecretForAlgorithm(anar_otp.SHA1)
if err != nil {
panic(err)
}
fmt.Println("Generated Secret:", secret)
}
HOTP Example
secret := []byte("mysecretkey")
hotp := anar_otp.NewHOTP(secret, 6, anar_otp.SHA1)
code, _ := hotp.Generate(uint64(1))
fmt.Println("HOTP code:", code)
valid, _ := hotp.Verify(code, uint64(1))
fmt.Println("HOTP valid?", valid)
TOTP Example
secretBase32 := "JBSWY3DPEHPK3PXP"
totp, _ := anar_otp.NewTOTP(secretBase32, nil)
code, _ := totp.Generate(time.Now())
fmt.Println("TOTP code:", code)
valid, _ := totp.Verify(code, time.Now())
fmt.Println("TOTP valid?", valid)
Generate QR Code
pngData, _ := totp.QRCodePNG("MyApp", "user@example.com", 256)
// Save pngData to file
base64Str, _ := totp.QRCodeBase64("MyApp", "user@example.com", 256)
fmt.Println("QR Code Base64:", base64Str)
Provisioning URI
uri, _ := totp.ProvisioningURI("MyApp", "user@example.com")
fmt.Println("Provisioning URI:", uri)
Configuration Options
- Digits: Number of digits (default 6)
- Algorithm: SHA1, SHA256, SHA512
- Period: Time period for TOTP (default 30s)
- Skew: Allowed clock skew for TOTP verification
Recommended secret lengths per algorithm:
| Algorithm | Secret Length (bytes) | | | | | SHA1 | 20 | | SHA256 | 32 | | SHA512 | 64 |
License
This library is licensed under the GNU Lesser General Public License (LGPL) v3.0.
Author
Ali Miracle