-
Notifications
You must be signed in to change notification settings - Fork 0
/
keygen.go
81 lines (66 loc) · 1.73 KB
/
keygen.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
package age
import (
"bytes"
"fmt"
"os"
"path/filepath"
"time"
"github.com/murtaza-u/z/age/agelib"
"filippo.io/age"
"github.com/seehuhn/password"
"github.com/urfave/cli/v2"
)
var keygenCmd = &cli.Command{
Name: "keygen",
Usage: "generates AGE public-private key pair",
UsageText: "keygen NAME",
Action: func(ctx *cli.Context) error {
k, err := age.GenerateX25519Identity()
if err != nil {
return err
}
_outF := ctx.Args().First()
if _outF == "" {
return fmt.Errorf("missing output file")
}
_outF = filepath.Join(Store, _outF)
defer func(k *age.X25519Identity) {
pub := fmt.Sprintf("%s\n", k.Recipient())
os.WriteFile(_outF+".pub", []byte(pub), 0600)
}(k)
pswd, err := password.Read("passphrase (optional): ")
if err != nil {
return fmt.Errorf("failed to read passphrase")
}
var _pswd []byte
if pswd != nil && len(pswd) != 0 {
_pswd, err = password.Read("confirm passphrase: ")
if err != nil {
return fmt.Errorf("failed to read passphrase")
}
}
if bytes.Compare(pswd, _pswd) != 0 {
return fmt.Errorf("passphrases do not match. Aborting!")
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "# created: %s\n", time.Now().Format(time.RFC3339))
fmt.Fprintf(buf, "# public key: %s\n", k.Recipient())
fmt.Fprintf(buf, "%s\n", k)
if pswd == nil || len(pswd) == 0 {
return os.WriteFile(_outF, buf.Bytes(), 0600)
}
r, err := age.NewScryptRecipient(string(pswd))
if err != nil {
return err
}
in := bytes.NewReader(buf.Bytes())
out := new(bytes.Buffer)
err = agelib.Encrypt(in, out, true, r)
if err != nil {
return fmt.Errorf(
"failed to encrypt private key with passphrase: %w",
err)
}
return os.WriteFile(_outF, out.Bytes(), 0600)
},
}