totp

package
v0.23.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 5, 2021 License: BSD-3-Clause Imports: 6 Imported by: 1

Documentation

Overview

Package totp implement Time-Based One-Time Password Algorithm based on RFC 6238 [1].

[1] https://tools.ietf.org/html/rfc6238

Index

Examples

Constants

View Source
const (
	// DefCodeDigits default digits generated when verifying or generating
	// OTP.
	DefCodeDigits = 6
	DefTimeStep   = 30
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Protocol

type Protocol struct {
	// contains filtered or unexported fields
}

Protocol contain methods to work with TOTP using the number of digits and time steps defined from New().

func New

func New(fnHash func() hash.Hash, codeDigits, timeStep int) Protocol

New create TOTP protocol for prover or verifier using "fnHash" as the hmac-sha hash function, "codeDigits" as the number of digits to be generated and/or verified, and "timeStep" as the time divisor.

func (*Protocol) Generate

func (p *Protocol) Generate(secret []byte) (otp string, err error)

Generate one time password using the secret and current timestamp.

func (*Protocol) GenerateN added in v0.22.0

func (p *Protocol) GenerateN(secret []byte, n int) (listOTP []string, err error)

GenerateN generate n number of passwords from (current time - N*timeStep) until the curent time.

func (*Protocol) Verify

func (p *Protocol) Verify(secret []byte, token string, stepsBack int) bool

Verify the token based on the prover secret key. It will return true if the token matched, otherwise it will return false.

The stepsBack parameter define number of steps in the pass to be checked for valid OTP. For example, if stepsBack = 2 and timeStep = 30, the time range to checking OTP is in between

(current_timestamp - (2*30)) ... current_timestamp

For security reason, the maximum stepsBack is limited to 4.

Example
secretHex := "3132333435363738393031323334353637383930"

secret, err := hex.DecodeString(secretHex)
if err != nil {
	log.Fatal(err)
}

p := New(sha1.New, DefCodeDigits, DefTimeStep)
otp, _ := p.Generate(secret)

if p.Verify(secret, otp, 1) {
	fmt.Printf("Generated token is valid.\n")
} else {
	fmt.Printf("Generated token is not valid.\n")
}
Output:

Generated token is valid.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL