-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hotp.go
118 lines (103 loc) · 2.27 KB
/
hotp.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
113
114
115
116
117
118
package otp
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base32"
"fmt"
"hash"
"math"
)
// otpauth://totp/Company:[email protected]?secret=[...]&issuer=Company
type HOTP struct {
seed string
window int
counter int
tokenLength int
base32 bool
encoding func() hash.Hash
}
func NewHOTP(seed string) HOTP {
return HOTP{
seed: seed,
encoding: sha1.New,
window: 5,
tokenLength: 6,
base32: true,
}
}
func (self HOTP) Base32(base32 bool) HOTP {
self.base32 = base32
return self
}
func (self HOTP) Counter(counter int) HOTP {
self.counter = counter
return self
}
func (self HOTP) TokenLength(tokenLength int) HOTP {
self.tokenLength = tokenLength
return self
}
func (self HOTP) Window(window int) HOTP {
self.window = window
return self
}
func (self HOTP) Encoding(encoding func() hash.Hash) HOTP {
self.encoding = encoding
return self
}
func (self HOTP) Seed() []byte {
if self.base32 {
encodedSeed, _ := base32.StdEncoding.DecodeString(self.seed)
return encodedSeed
} else {
return []byte(self.seed)
}
}
func (self HOTP) HMAC() []byte {
hash := hmac.New(self.encoding, self.Seed())
hash.Write([]byte(counterToBytes(self.counter)))
return hash.Sum(nil)
}
func (self HOTP) Generate() string {
otp := truncate(self.HMAC()) % int(math.Pow10(self.tokenLength))
return fmt.Sprintf(fmt.Sprintf("%%0%dd", self.tokenLength), otp)
}
func (self HOTP) Check(otp string) (bool, int) {
for i := 0; i < self.window; i++ {
o := self.Generate()
if o == otp {
return true, int(self.counter)
}
self.counter++
}
return false, 0
}
func (self HOTP) Sync(otp1 string, otp2 string) (bool, int) {
self.window = 100
v, i := self.Check(otp1)
if !v {
return false, 0
}
self.counter = self.counter + i + 1
self.window = 1
v2, i2 := self.Check(otp2)
if v2 {
return true, i2 + 1
}
return false, 0
}
func truncate(hash []byte) int {
offset := int(hash[len(hash)-1] & 0xf)
return ((int(hash[offset]) & 0x7f) << 24) |
((int(hash[offset+1] & 0xff)) << 16) |
((int(hash[offset+2] & 0xff)) << 8) |
(int(hash[offset+3]) & 0xff)
}
func counterToBytes(counter int) (text []byte) {
text = make([]byte, 8)
for i := (len(text) - 1); i >= 0; i-- {
text[i] = byte(counter & 0xff)
counter = counter >> 8
}
return text
}