/go-otp

Golang implementation of the OTP (One Time Password) algorithms.

Primary LanguageGoMIT LicenseMIT

go-otp

test Go Report Card codecov Version Badge License Badge Go Reference

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.

  • TOTP: Time-based One-Time Password (RFC 6238)
  • HOTP: HMAC-based One-Time Password (RFC 4226)

Features

  • 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

Installation

go get github.com/ghosind/go-otp

Quick Start

package 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)
}

API Reference

TOTP

  • NewTOTP(options...) creates a TOTP instance
  • Generate(secret []byte) generates a code for the current time
  • GenerateWithTime(t time.Time, secret []byte) generates a code for a specific time

HOTP

  • NewHOTP(options...) creates a HOTP instance
  • Generate(counter uint64, secret []byte) generates a code for a given counter

Testing

The project includes RFC 6238 standard test vectors to ensure algorithm correctness.

Run tests:

go test ./...

License

This project is licensed under the MIT License. See the LICENSE file for details.