-
Notifications
You must be signed in to change notification settings - Fork 0
/
totp.go
112 lines (85 loc) · 2.33 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package otp
import (
"crypto"
"encoding/base32"
)
// TOTP interface
type TOTP interface {
// Get interval
Interval() uint32
// Set interval
SetInterval(uint32)
// Generate a TOTP password
Generate(digitCount uint8) (uint32, int)
// Generate a TOTP password as a string
GenerateString(digitCount uint8) (string, int)
// Generate a 4-digit HOTP password
Generate4() (uint32, int)
// Generate a 4-digit HOTP password as a string
GenerateString4() (string, int)
// Generate a 6-digit HOTP password
Generate6() (uint32, int)
// Generate a 6-digit HOTP password as a string
GenerateString6() (string, int)
// Generate an 8-digit HOTP password
Generate8() (uint32, int)
// Generate an 8-digit HOTP password as a string
GenerateString8() (string, int)
}
type totpAdapter struct {
hotp HOTP
counter uint64
delta int
interval uint32
}
func (totp *totpAdapter) updateTime() {
totp.counter, totp.delta = calcTimeBasedCounter(totp.interval)
totp.hotp.SetCounter(totp.counter)
}
func (totp *totpAdapter) Interval() uint32 {
return totp.interval
}
func (totp *totpAdapter) SetInterval(interval uint32) {
totp.interval = interval
}
func (totp *totpAdapter) Generate(digitCount uint8) (uint32, int) {
totp.updateTime()
return totp.hotp.Generate(digitCount), totp.delta
}
func (totp *totpAdapter) GenerateString(digitCount uint8) (string, int) {
totp.updateTime()
return totp.hotp.GenerateString(digitCount), totp.delta
}
func (totp *totpAdapter) Generate4() (uint32, int) {
return totp.Generate(4)
}
func (totp *totpAdapter) GenerateString4() (string, int) {
return totp.GenerateString(4)
}
func (totp *totpAdapter) Generate6() (uint32, int) {
return totp.Generate(6)
}
func (totp *totpAdapter) GenerateString6() (string, int) {
return totp.GenerateString(6)
}
func (totp *totpAdapter) Generate8() (uint32, int) {
return totp.Generate(8)
}
func (totp *totpAdapter) GenerateString8() (string, int) {
return totp.GenerateString(8)
}
func NewTOTPBase32(base32Secret string, algorithm crypto.Hash) (TOTP, error) {
secret, err := base32.StdEncoding.DecodeString(base32Secret)
if err != nil {
return nil, err
}
return NewTOTP(secret, algorithm), nil
}
func NewTOTP(secret []byte, algorithm crypto.Hash) TOTP {
return &totpAdapter{
hotp: NewHOTP(secret, algorithm),
interval: 30,
counter: 0,
delta: 0,
}
}