forked from openp2p-cn/totp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
totp.go
41 lines (36 loc) · 875 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
// Time-based One-time Password
package totp
import (
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
)
const RelayTOTPStep = 30
const ForgotPwdTOTPStep = 300
type TOTP struct {
Step int64 // relay 30s; forgot password 300s;
}
func (t *TOTP) Gen(token uint64, ts int64) uint64 {
step := ts / t.Step
tbuff := make([]byte, 8)
binary.LittleEndian.PutUint64(tbuff, token)
mac := hmac.New(sha256.New, tbuff)
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, uint64(step))
mac.Write(b)
num := binary.LittleEndian.Uint64(mac.Sum(nil)[:8])
// fmt.Printf("%x\n", mac.Sum(nil))
return num
}
func (t *TOTP) Verify(code uint64, token uint64, ts int64) bool {
if code == 0 {
return false
}
if code == token {
return true
}
if code == t.Gen(token, ts) || code == t.Gen(token, ts-t.Step) || code == t.Gen(token, ts+t.Step) {
return true
}
return false
}