/
totp.go
60 lines (52 loc) · 1.4 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
package crypto
import (
"crypto/rand"
"encoding/hex"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
)
const (
totpIssuerName = "Inertia"
totpPeriod = 30
totpSecretSize = 10
totpDigits = 6
totpAlgorithm = otp.AlgorithmSHA1
totpNoBackupCodes = 10
totpBackupCodeLength = 5
)
// GenerateSecretKey creates a new key which can be turned into string or image
func GenerateSecretKey(accountName string) (*otp.Key, error) {
return totp.Generate(totp.GenerateOpts{
Issuer: totpIssuerName,
AccountName: accountName,
Period: totpPeriod,
SecretSize: totpSecretSize,
Digits: totpDigits,
Algorithm: totpAlgorithm,
})
}
// ValidatePasscode validates one-time passcode against original secret key
func ValidatePasscode(passcode string, secret string) bool {
return totp.Validate(passcode, secret)
}
// GenerateBackupCodes generates an array of backup code strings in
// Github format.
//
// Example:
// b2e03-ffbcf
// cebe6-b1bdd
// ...
func GenerateBackupCodes() []string {
backupCodes := make([]string, totpNoBackupCodes)
for i := 0; i < totpNoBackupCodes; i++ {
// get random bytes
randomBytes := make([]byte, totpBackupCodeLength)
rand.Read(randomBytes)
// convert to hex string
codeHex := hex.EncodeToString(randomBytes)
// split with dash
code := codeHex[:5] + "-" + codeHex[5:]
backupCodes[i] = code
}
return backupCodes
}