go-otp is a Go library for generating OTP (One-Time Password) codes. It currently supports TOTP (Time-based One-Time Password, RFC 6238) and is suitable for two-factor authentication, dynamic password, and other security scenarios.
- Supports multiple hash algorithms: SHA1, SHA256, SHA512
- Customizable code length and period
- Compatible with popular TOTP apps (e.g., Google Authenticator)
- Simple and easy-to-use API
go get github.com/ghosind/go-otppackage main
import (
"fmt"
"time"
"github.com/ghosind/go-otp"
)
func main() {
secret := []byte("your-secret-key")
totp := otp.NewTOTP(
otp.WithAlgorithm(otp.AlgHmacSha1),
otp.WithDigits(6),
otp.WithPeriod(30),
)
code, err := totp.Generate(secret)
if err != nil {
panic(err)
}
fmt.Println("TOTP Code:", code)
// Generate code for a specific time
customTime := time.Now()
code, _ = totp.GenerateWithTime(customTime, secret)
fmt.Println("Custom Time TOTP:", code)
}NewTOTP(options...)creates a TOTP instanceGenerate(secret []byte)generates a code for the current timeGenerateWithTime(t time.Time, secret []byte)generates a code for a specific time
NewHOTP(options...)creates a HOTP instanceGenerate(counter uint64, secret []byte)generates a code for a given counter
The project includes RFC 6238 standard test vectors to ensure algorithm correctness.
Run tests:
go test ./...This project is licensed under the MIT License. See the LICENSE file for details.