/
next.go
58 lines (45 loc) · 1.26 KB
/
next.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
package moths
import (
"crypto/hmac"
"crypto/sha1"
"encoding/binary"
"fmt"
"math"
"time"
"github.com/Mobilpadde/moths/v4/moths/otp"
)
func (m *Moths) Next() (otp.OTP, error) {
token, err := m.getToken()
if err != nil {
return otp.OTP{}, err
}
return otp.NewOTP(token, m.amount, m.emojies)
}
func (m *Moths) getToken() (string, error) {
m.timing.curr = time.Now().UTC()
since := m.timing.curr.Sub(m.timing.last)
if since < m.interval {
return m.lastToken, nil
}
m.timing.last = m.timing.curr
m.timing.time = m.timing.time.Add(since)
interval := uint64(m.timing.time.Unix() / int64(m.interval.Seconds()))
// https://github.com/pquerna/otp/blob/master/hotp/hotp.go#L95-L123
buf := make([]byte, 8)
h := hmac.New(sha1.New, m.secret)
binary.BigEndian.PutUint64(buf, interval)
h.Write(buf)
sum := h.Sum(nil)
// "Dynamic truncation" in RFC 4226
// http://tools.ietf.org/html/rfc4226#section-5.4
offset := sum[len(sum)-1] & 0xf
value := int64(((int(sum[offset]) & 0x7f) << 24) |
((int(sum[offset+1] & 0xff)) << 16) |
((int(sum[offset+2] & 0xff)) << 8) |
(int(sum[offset+3]) & 0xff))
f := fmt.Sprintf("%%0%dd", m.amount)
mod := int32(value % int64(math.Pow10(m.amount)))
token := fmt.Sprintf(f, mod)
m.lastToken = token
return token, nil
}