-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtotp.go
More file actions
77 lines (63 loc) · 1.34 KB
/
totp.go
File metadata and controls
77 lines (63 loc) · 1.34 KB
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
package main
import (
"encoding/base32"
"fmt"
"net/url"
"os/user"
)
type totp struct {
algorithm Algorithm
digits Digits
period Period
secret []byte
}
func NewTOTP(algorithm Algorithm, digits Digits, period Period) *totp {
secret := generateSecret(algorithm)
return &totp {
algorithm,
digits,
period,
secret,
}
}
func (t *totp) Algorithm() Algorithm {
return t.algorithm
}
func (t *totp) Secret() []byte {
return t.secret
}
// TODO - implement
func (t *totp) GenerateURI() string {
user, err := user.Current()
if err != nil {
panic(err)
}
queryParms := url.Values {
"algorithm": { string(t.algorithm) },
"digits": { fmt.Sprintf("%d", t.digits) },
"issuer": { issuer },
"period": { fmt.Sprintf("%d", t.period) },
"secret": { base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(t.secret) },
}
url := url.URL {
Scheme: "otpauth",
Host: "totp",
Path: fmt.Sprintf("%s:%s", issuer, user.Name),
RawQuery: queryParms.Encode(),
}
return url.String()
}
func (t *totp) GenerateOTP(seconds int64) string {
steps := uint64(seconds) / uint64(t.period)
return t.toHOTP().GenerateOTP(steps)
}
func (t *totp) ValidateOTP(seconds int64, otp string) bool {
return t.GenerateOTP(seconds) == otp
}
func (t* totp) toHOTP() *hotp {
return &hotp {
algorithm: t.algorithm,
digits: t.digits,
secret: t.secret,
}
}