Debian Codegraph @

totp.go

raw symbols SCIP
1 package gotp
2
3 import "time"
4
5 // time-based OTP counters.
6 type TOTP struct {
7 OTP
8 interval int
9 }
10
11 func NewTOTP(secret string, digits, interval int, hasher *Hasher) *TOTP {
12 otp := NewOTP(secret, digits, hasher)
13 return &TOTP{OTP: otp, interval: interval}
14 }
15
16 func NewDefaultTOTP(secret string) *TOTP {
17 return NewTOTP(secret, 6, 30, nil)
18 }
19
20 // Generate time OTP of given timestamp
21 func (t *TOTP) At(timestamp int) string {
22 return t.generateOTP(t.timecode(timestamp))
23 }
24
25 // Generate the current time OTP
26 func (t *TOTP) Now() string {
27 return t.At(currentTimestamp())
28 }
29
30 // Generate the current time OTP and expiration time
31 func (t *TOTP) NowWithExpiration() (string, int64) {
32 interval64 := int64(t.interval)
33 timeCodeInt64 := time.Now().Unix() / interval64
34 expirationTime := (timeCodeInt64 + 1) * interval64
35 return t.generateOTP(int(timeCodeInt64)), expirationTime
36 }
37
38 /*
39 Verify OTP.
40
41 params:
42 otp: the OTP to check against
43 timestamp: time to check OTP at
44 */
45 func (t *TOTP) Verify(otp string, timestamp int) bool {
46 return otp == t.At(timestamp)
47 }
48
49 /*
50 Returns the provisioning URI for the OTP.
51 This can then be encoded in a QR Code and used to provision an OTP app like Google Authenticator.
52
53 See also:
54 https://github.com/google/google-authenticator/wiki/Key-Uri-Format
55
56 params:
57 accountName: name of the account
58 issuerName: the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator
59
60 returns: provisioning URI
61 */
62 func (t *TOTP) ProvisioningUri(accountName, issuerName string) string {
63 return BuildUri(
64 OtpTypeTotp,
65 t.secret,
66 accountName,
67 issuerName,
68 t.hasher.HashName,
69 0,
70 t.digits,
71 t.interval)
72 }
73
74 func (t *TOTP) timecode(timestamp int) int {
75 return int(timestamp / t.interval)
76 }