github.hscsec.cn/hashicorp/consul@v1.4.5/command/keygen/keygen.go (about) 1 package keygen 2 3 import ( 4 "crypto/rand" 5 "encoding/base64" 6 "flag" 7 "fmt" 8 9 "github.com/hashicorp/consul/command/flags" 10 "github.com/mitchellh/cli" 11 ) 12 13 func New(ui cli.Ui) *cmd { 14 c := &cmd{UI: ui} 15 c.init() 16 return c 17 } 18 19 type cmd struct { 20 UI cli.Ui 21 flags *flag.FlagSet 22 help string 23 } 24 25 func (c *cmd) init() { 26 c.flags = flag.NewFlagSet("", flag.ContinueOnError) 27 c.help = flags.Usage(help, c.flags) 28 } 29 30 func (c *cmd) Run(args []string) int { 31 if err := c.flags.Parse(args); err != nil { 32 return 1 33 } 34 35 key := make([]byte, 16) 36 n, err := rand.Reader.Read(key) 37 if err != nil { 38 c.UI.Error(fmt.Sprintf("Error reading random data: %s", err)) 39 return 1 40 } 41 if n != 16 { 42 c.UI.Error(fmt.Sprintf("Couldn't read enough entropy. Generate more entropy!")) 43 return 1 44 } 45 46 c.UI.Output(base64.StdEncoding.EncodeToString(key)) 47 return 0 48 } 49 50 func (c *cmd) Synopsis() string { 51 return synopsis 52 } 53 54 func (c *cmd) Help() string { 55 return c.help 56 } 57 58 const synopsis = "Generates a new encryption key" 59 const help = ` 60 Usage: consul keygen 61 62 Generates a new encryption key that can be used to configure the 63 agent to encrypt traffic. The output of this command is already 64 in the proper format that the agent expects. 65 `