Featured image of post OTP / TOTP

OTP / TOTP

import

1
2
3
4
import (
	"github.com/pquerna/otp"
	"github.com/pquerna/otp/totp"
)

Generate totp key

1
2
3
4
5
key, err := totp.Generate(totp.GenerateOpts{
    Issuer:      "system",
    AccountName: "user",
    Digits:      digitalLen,  // default is 6
})

Sharing code

by url

1
key.URL()

by image

1
img, err := key.Image(256, 256)

by printing to console

1
import "github.com/skip2/go-qrcode"
1
2
3
4
5
6
qr, err := qrcode.New(key.URL(), qrcode.Medium)
if err != nil {
    panic(err)
}

fmt.Println(qr.ToSmallString(true))

ValidateOpts

1
2
3
4
5
6
validateOpts := totp.ValidateOpts{
    Period:    30,
    Skew:      1,
    Digits:    digitalLen,
    Algorithm: otp.AlgorithmSHA1,
}

GenerateCode

1
2
3
4
5
code, err := totp.GenerateCodeCustom(key.Secret(), time.Now(), validateOpts)
if err != nil {
    panic(err)
}
fmt.Println(code)

Validate

1
success, err := totp.ValidateCustom(code, key.Secret(), time.Now(), validateOpts)
Licensed under CC BY-NC-SA 4.0