Newer
Older
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
89
90
91
92
93
94
95
96
97
package totpmdl
import (
"bytes"
"image/png"
"time"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/loggermdl"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
)
type TOTPGenerate struct {
// Name of the issuing Organization/Company/application.
Issuer string
// Name of the User's Account (eg, email address)
AccountName string
// Number of seconds a TOTP hash is valid for. Defaults to 30 seconds.
Period uint
// Size in size of the generated Secret. Defaults to 20 bytes.
SecretSize uint
// Secret to store. Defaults to a randomly generated secret of SecretSize. You should generally leave this empty.
// Secret []byte
// Digits to request. Defaults to 6.
Digits otp.Digits
// Algorithm to use for HMAC. Defaults to SHA1.
Algorithm otp.Algorithm
// Reader to use for generating TOTP Key.
// Rand io.Reader
}
type TOTPValidate struct {
//OTP Generated by authenticator application
Token string
//secret key
Secret string
// Number of seconds a TOTP hash is valid for. Defaults to 30 seconds.
Period uint
// Periods before or after the current time to allow. Value of 1 allows up to Period
// of either side of the specified time. Defaults to 0 allowed skews. Values greater
// than 1 are likely sketchy.
Skew uint
// Digits to request. Defaults to 6.
Digits otp.Digits
// Algorithm to use for HMAC. Defaults to SHA1.
Algorithm otp.Algorithm
}
//generate QR
func (t *TOTPGenerate) NewQR(key *otp.Key) ([]byte, error) {
var buf bytes.Buffer
img, errImage := key.Image(500, 500) //set dimenions of qr image
if errImage != nil {
return nil, errImage
}
imageCreateErr := png.Encode(&buf, img) //encode the Image.Image to buffer
if imageCreateErr != nil {
return nil, imageCreateErr
}
return buf.Bytes(), nil //return image in bytes() format
}
//create totp secret key
func (t *TOTPGenerate) CreateSecretKey() (*otp.Key, error) {
key, keyGenErr := totp.Generate(totp.GenerateOpts{
Issuer: t.Issuer,
AccountName: t.AccountName,
SecretSize: t.SecretSize,
Period: t.Period,
Digits: t.Digits,
Algorithm: t.Algorithm,
})
if keyGenErr != nil {
return nil, keyGenErr
}
return key, nil
}
//validate totp code
func (v *TOTPValidate) ValidateTOTP() (bool, error) {
isValid, errValidation := totp.ValidateCustom( // you can also use the validate method but it will not allow you customizations
v.Token,
v.Secret,
time.Now().UTC(),
totp.ValidateOpts{
Period: v.Period,
Skew: v.Skew,
Digits: v.Digits,
Algorithm: v.Algorithm,
},
)
if errValidation != nil {
loggermdl.LogError("Error in totp validation:", errValidation.Error())
return isValid, errValidation
}
return isValid, nil
}