-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtotp.go
88 lines (76 loc) · 2.11 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
// Package totp is an implementation of Time-Based One-Time Passwords as
// described in IETF RFC 6238. See https://tools.ietf.org/html/rfc6238
package totp
import (
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"fmt"
"hash"
"time"
)
// Generator holds the state to calculate Time-Based One-Time Passwords as
// described in IETF RFC 6238. See https://tools.ietf.org/html/rfc6238
type Generator struct {
key []byte
t0 time.Time
tx time.Duration
f func() hash.Hash
}
// NewSha1 returns a Generator using the provided key, Sha1 hashes, a start time
// at the Unix epoch and a time step of 30 seconds.
func NewSha1(key []byte) Generator {
return Totp{
key: key,
t0: time.Unix(0, 0),
tx: 30 * time.Second,
f: sha1.New,
}
}
// NewSha256 returns a Generator using the provided key, Sha256 hashes, a start
// time at the Unix epoch and a time step of 30 seconds.
func NewSha256(key []byte) Generator {
return Totp{
key: key,
t0: time.Unix(0, 0),
tx: 30 * time.Second,
f: sha256.New,
}
}
// NewSha512 returns a Generator using the provided key, Sha512 hashes, a start
// time at the Unix epoch and a time step of 30 seconds.
func NewSha512(key []byte) Generator {
return Totp{
key: key,
t0: time.Unix(0, 0),
tx: 30 * time.Second,
f: sha512.New,
}
}
// At returns the value of the one-time password at the time t.
func (g Generator) At(t time.Time) string {
// calculate the time step
ct := t.Sub(g.t0).Nanoseconds() / g.tx.Nanoseconds()
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(ct))
// calculate the hash
h := hmac.New(g.f, g.key)
h.Write(b)
c := h.Sum(nil)
// apply a window to select 4 bytes
i := c[len(c)-1] & 0xf
u := binary.BigEndian.Uint32(c[i : i+5])
// calculate the final value
p := (u & 0x7fffffff) % 1e6
return fmt.Sprintf("%06d", p)
}
// In returns the value of the one-time password after the duration d.
func (g Generator) In(d time.Duration) string {
return g.At(time.Now().Add(d))
}
// Now returns the value of the one-time password at the time of calling.
func (g Generator) Now() string {
return g.At(time.Now())
}