-
Notifications
You must be signed in to change notification settings - Fork 0
/
totp.go
41 lines (33 loc) · 965 Bytes
/
totp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package totp
import (
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"github.com/nciont/totp/util"
"hash"
"strconv"
)
func NewTOTP(secret []byte, hasher func() hash.Hash, stepper func(uint64) uint64) *TOTP {
return &TOTP{NewHOTP(hasher, secret), stepper}
}
func NewSHA1TOTP(secret []byte) *TOTP {
return NewTOTP(secret, sha1.New, util.TimeStepper)
}
func NewSHA256TOTP(secret []byte) *TOTP {
return NewTOTP(secret, sha256.New, util.TimeStepper)
}
func NewSHA512TOTP(secret []byte) *TOTP {
return NewTOTP(secret, sha512.New, util.TimeStepper)
}
type TOTP struct {
*HOTP
Stepper func(uint64) uint64
}
func (totp *TOTP) Compute(time uint64, digits int) int {
totp.hmacImpl.Reset()
totp.hmacImpl.Write(util.IntBytes(totp.Stepper(time)))
return util.GetDigits(getCode(totp.hmacImpl.Sum(nil)), digits)
}
func (totp *TOTP) ComputeString(time uint64, digits int) string {
return util.PadStart(strconv.Itoa(totp.Compute(time, digits)), "0", digits)
}