-
-
Notifications
You must be signed in to change notification settings - Fork 479
/
otp.go
69 lines (59 loc) · 1.53 KB
/
otp.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
61
62
63
64
65
66
67
68
69
package otp
import (
"fmt"
"os"
"strings"
"github.com/gokyle/twofactor"
"github.com/gopasspw/gopass/pkg/gopass"
)
// Calculate will compute a OTP code from a given secret
func Calculate(name string, sec gopass.Secret) (twofactor.OTP, string, error) {
otpURL, found := sec.Get("otpauth")
if found && strings.HasPrefix(otpURL, "//") {
otpURL = "otpauth:" + otpURL
} else {
// check body
for _, line := range strings.Split(sec.Body(), "\n") {
if strings.HasPrefix(line, "otpauth://") {
otpURL = line
break
}
}
}
if otpURL != "" {
return twofactor.FromURL(otpURL)
}
// check yaml entry and fall back to password if we don't have one
label := name
secKey, found := sec.Get("totp")
if !found {
secKey = sec.Password()
}
if strings.HasPrefix(secKey, "otpauth://") {
return twofactor.FromURL(secKey)
}
otp, err := twofactor.NewGoogleTOTP(twofactor.Pad(secKey))
return otp, label, err
}
// WriteQRFile writes the given OTP code as a QR image to disk
func WriteQRFile(otp twofactor.OTP, label, file string) error {
var qr []byte
var err error
switch otp.Type() {
case twofactor.OATH_HOTP:
hotp := otp.(*twofactor.HOTP)
qr, err = hotp.QR(label)
case twofactor.OATH_TOTP:
totp := otp.(*twofactor.TOTP)
qr, err = totp.QR(label)
default:
err = fmt.Errorf("QR codes can only be generated for OATH OTPs")
}
if err != nil {
return fmt.Errorf("failed to write qr file: %w", err)
}
if err := os.WriteFile(file, qr, 0600); err != nil {
return fmt.Errorf("failed to write QR code: %w", err)
}
return nil
}