| 1 |
package gotp |
| 2 |
|
| 3 |
import "time" |
| 4 |
|
| 5 |
|
| 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 |
|
| 21 |
func (t *TOTP) At(timestamp int) string { |
| 22 |
return t.generateOTP(t.timecode(timestamp)) |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
func (t *TOTP) Now() string { |
| 27 |
return t.At(currentTimestamp()) |
| 28 |
} |
| 29 |
|
| 30 |
|
| 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 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
func (t *TOTP) Verify(otp string, timestamp int) bool { |
| 46 |
return otp == t.At(timestamp) |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 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 |
} |