OTP 是 One-Time Password的简写,表示一次性密码。
HOTP 是HMAC-based One-Time Password的简写,表示基于HMAC算法加密的一次性密码。
TOTP 是Time-based One-Time Password的简写,表示基于时间戳算法的一次性密码。

TOTP 是时间同步,基于客户端的动态口令和动态口令验证服务器的时间比对,一般每30秒产生一个新口令,要求客户端和服务器能够十分精确的保持正确的时钟,客户端和服务端基于时间计算的动态口令才能一致。

HOTP 是事件同步,通过某一特定的事件次序及相同的种子值作为输入,通过HASH算法运算出一致的密码。

文档:https://pkg.go.dev/github.com/pquerna/otp

type Key

  1. type Key struct {
  2. // contains filtered or unexported fields
  3. }
  4. func NewKeyFromURL(orig string) (*Key, error)
  5. func (k *Key) AccountName() string
  6. func (k *Key) Image(width int, height int) (image.Image, error)
  7. func (k *Key) Issuer() string
  8. func (k *Key) Period() uint64
  9. func (k *Key) Secret() string
  10. func (k *Key) String() string
  11. func (k *Key) Type() string // "hotp" or "totp"
  12. func (k *Key) URL() string

topt

  1. func Generate(opts GenerateOpts) (*otp.Key, error)
  2. func Validate(passcode string, secret string) bool
  3. type GenerateOpts struct {
  4. // Name of the issuing Organization/Company.
  5. Issuer string
  6. // Name of the User's Account (eg, email address)
  7. AccountName string
  8. // Number of seconds a TOTP hash is valid for. Defaults to 30 seconds.
  9. Period uint
  10. // Size in size of the generated Secret. Defaults to 20 bytes.
  11. SecretSize uint
  12. // Secret to store. Defaults to a randomly generated secret of SecretSize. You should generally leave this empty.
  13. Secret []byte
  14. // Digits to request. Defaults to 6.
  15. Digits otp.Digits
  16. // Algorithm to use for HMAC. Defaults to SHA1.
  17. Algorithm otp.Algorithm
  18. // Reader to use for generating TOTP Key.
  19. Rand io.Reader
  20. }
  21. type ValidateOpts struct {
  22. // Number of seconds a TOTP hash is valid for. Defaults to 30 seconds.
  23. Period uint
  24. // Periods before or after the current time to allow. Value of 1 allows up to Period
  25. // of either side of the specified time. Defaults to 0 allowed skews. Values greater
  26. // than 1 are likely sketchy.
  27. Skew uint
  28. // Digits as part of the input. Defaults to 6.
  29. Digits otp.Digits
  30. // Algorithm to use for HMAC. Defaults to SHA1.
  31. Algorithm otp.Algorithm
  32. }

demo(topt)

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/pquerna/otp/totp"
  5. "time"
  6. )
  7. func main() {
  8. var opt = totp.GenerateOpts{
  9. Issuer:"jwrookie",
  10. AccountName:"jw",
  11. }
  12. key,err := totp.Generate(opt)
  13. if err != nil {
  14. panic(err)
  15. }
  16. fmt.Println(key.URL())
  17. passcode,_ := totp.GenerateCode(key.Secret(),time.Now())
  18. fmt.Println(totp.Validate(passcode,key.Secret()))
  19. }
  20. otpauth://totp/jwrookie:jw?algorithm=SHA1&digits=6&issuer=jwrookie&period=30&secret=CBLVFFGOHYWYFIRM5XVL3WG6JQC4YSGY
  21. true