- Key">type Key
- topt
- demo(topt)
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
type Key struct {
// contains filtered or unexported fields
}
func NewKeyFromURL(orig string) (*Key, error)
func (k *Key) AccountName() string
func (k *Key) Image(width int, height int) (image.Image, error)
func (k *Key) Issuer() string
func (k *Key) Period() uint64
func (k *Key) Secret() string
func (k *Key) String() string
func (k *Key) Type() string // "hotp" or "totp"
func (k *Key) URL() string
topt
func Generate(opts GenerateOpts) (*otp.Key, error)
func Validate(passcode string, secret string) bool
type GenerateOpts struct {
// Name of the issuing Organization/Company.
Issuer string
// Name of the User's Account (eg, email address)
AccountName string
// Number of seconds a TOTP hash is valid for. Defaults to 30 seconds.
Period uint
// Size in size of the generated Secret. Defaults to 20 bytes.
SecretSize uint
// Secret to store. Defaults to a randomly generated secret of SecretSize. You should generally leave this empty.
Secret []byte
// Digits to request. Defaults to 6.
Digits otp.Digits
// Algorithm to use for HMAC. Defaults to SHA1.
Algorithm otp.Algorithm
// Reader to use for generating TOTP Key.
Rand io.Reader
}
type ValidateOpts struct {
// Number of seconds a TOTP hash is valid for. Defaults to 30 seconds.
Period uint
// Periods before or after the current time to allow. Value of 1 allows up to Period
// of either side of the specified time. Defaults to 0 allowed skews. Values greater
// than 1 are likely sketchy.
Skew uint
// Digits as part of the input. Defaults to 6.
Digits otp.Digits
// Algorithm to use for HMAC. Defaults to SHA1.
Algorithm otp.Algorithm
}
demo(topt)
package main
import (
"fmt"
"github.com/pquerna/otp/totp"
"time"
)
func main() {
var opt = totp.GenerateOpts{
Issuer:"jwrookie",
AccountName:"jw",
}
key,err := totp.Generate(opt)
if err != nil {
panic(err)
}
fmt.Println(key.URL())
passcode,_ := totp.GenerateCode(key.Secret(),time.Now())
fmt.Println(totp.Validate(passcode,key.Secret()))
}
otpauth://totp/jwrookie:jw?algorithm=SHA1&digits=6&issuer=jwrookie&period=30&secret=CBLVFFGOHYWYFIRM5XVL3WG6JQC4YSGY
true