github.com/blixtra/nomad@v0.7.2-0.20171221000451-da9a1d7bb050/command/keygen.go (about)

     1  package command
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/base64"
     6  	"fmt"
     7  	"strings"
     8  )
     9  
    10  // KeygenCommand is a Command implementation that generates an encryption
    11  // key for use in `nomad agent`.
    12  type KeygenCommand struct {
    13  	Meta
    14  }
    15  
    16  func (c *KeygenCommand) Synopsis() string {
    17  	return "Generates a new encryption key"
    18  }
    19  
    20  func (c *KeygenCommand) Help() string {
    21  	helpText := `
    22  Usage: nomad 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  
    31  func (c *KeygenCommand) Run(_ []string) int {
    32  	key := make([]byte, 16)
    33  	n, err := rand.Reader.Read(key)
    34  	if err != nil {
    35  		c.Ui.Error(fmt.Sprintf("Error reading random data: %s", err))
    36  		return 1
    37  	}
    38  	if n != 16 {
    39  		c.Ui.Error(fmt.Sprintf("Couldn't read enough entropy. Generate more entropy!"))
    40  		return 1
    41  	}
    42  
    43  	c.Ui.Output(base64.StdEncoding.EncodeToString(key))
    44  	return 0
    45  }