-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
108 lines (98 loc) · 2.44 KB
/
utils.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
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
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"bytes"
"crypto/rand"
"errors"
"fmt"
"log"
"math/big"
"os"
"path/filepath"
"strings"
"github.com/go-piv/piv-go/piv"
"golang.org/x/term"
)
func randomSerialNumber() *big.Int {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
log.Fatalln("Failed to generate serial number:", err)
}
return serialNumber
}
func ensureYK(yk *piv.YubiKey) error {
_, err := yk.AttestationCertificate()
healthy := err == nil
if yk == nil || !healthy {
if yk != nil {
log.Println("Reconnecting to the YubiKey...")
yk.Close()
} else {
log.Println("Connecting to the YubiKey...")
}
}
return nil
}
func getPINPrompt() []byte {
fmt.Print("Input your PIN/PUK: ")
pin, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Print("\n")
if err != nil {
log.Fatalln("Failed to read PIN:", err)
}
if len(pin) == 0 || len(pin) > 8 {
log.Fatalln("The PIN needs to be 6 - 8 characters.")
}
return pin
}
func setPinPrompt() []byte {
fmt.Print("Choose a new 6-8 bit PIN/PUK: ")
pin, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Print("\n")
if err != nil {
log.Fatalln("Failed to read PIN:", err)
}
if len(pin) == 0 || len(pin) > 8 {
log.Fatalln("The PIN needs to be 6 - 8 characters.")
}
fmt.Print("Repeat PIN/PUK: ")
repeat, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Print("\n")
if err != nil {
log.Fatalln("Failed to read PIN:", err)
} else if !bytes.Equal(repeat, pin) {
log.Fatalln("PINs don't match!")
}
return pin
}
func checkObjects(core *Core) error {
if core.Pub == nil {
return errors.New("ECDSA Public Key Empty")
}
if core.Priv == nil {
return errors.New("YubiKey ECDSA Private Key Empty")
}
if core.YK == nil {
return errors.New("yubikey engine empty")
}
if core.ManagementKey[:] == nil {
return errors.New("management key empty")
}
if core.Pin == nil {
return errors.New("pin empty")
}
return nil
}
func setFilename(targetFilename string, pattern string) string {
var outfileName string
switch pattern {
case "decrypt":
realfileName := strings.ReplaceAll(targetFilename, "_encrypted.bin", "")
withoutExtension := strings.TrimSuffix(realfileName, filepath.Ext(realfileName))
outfileName = strings.ReplaceAll(realfileName, withoutExtension, withoutExtension+"_decrypted")
log.Println(outfileName)
case "encrypt":
outfileName = targetFilename + "_encrypted" + ".bin"
}
return outfileName
}