1package command
2
3import (
4	"crypto/rand"
5	"encoding/base64"
6	"fmt"
7	"strings"
8)
9
10// OperatorKeygenCommand is a Command implementation that generates an encryption
11// key for use in `nomad agent`.
12type OperatorKeygenCommand struct {
13	Meta
14}
15
16func (c *OperatorKeygenCommand) Synopsis() string {
17	return "Generates a new encryption key"
18}
19
20func (c *OperatorKeygenCommand) Help() string {
21	helpText := `
22Usage: nomad operator keygen
23
24  Generates a new encryption key that can be used to configure the
25  agent to encrypt traffic. The output of this command is already
26  in the proper format that the agent expects.
27`
28	return strings.TrimSpace(helpText)
29}
30
31func (c *OperatorKeygenCommand) Name() string { return "operator keygen" }
32
33func (c *OperatorKeygenCommand) Run(_ []string) int {
34	key := make([]byte, 16)
35	n, err := rand.Reader.Read(key)
36	if err != nil {
37		c.Ui.Error(fmt.Sprintf("Error reading random data: %s", err))
38		return 1
39	}
40	if n != 16 {
41		c.Ui.Error(fmt.Sprintf("Couldn't read enough entropy. Generate more entropy!"))
42		return 1
43	}
44
45	c.Ui.Output(base64.StdEncoding.EncodeToString(key))
46	return 0
47}
48