github.com/slackhq/nebula@v1.9.0/cmd/nebula-cert/keygen.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  
     9  	"github.com/slackhq/nebula/cert"
    10  )
    11  
    12  type keygenFlags struct {
    13  	set        *flag.FlagSet
    14  	outKeyPath *string
    15  	outPubPath *string
    16  
    17  	curve *string
    18  }
    19  
    20  func newKeygenFlags() *keygenFlags {
    21  	cf := keygenFlags{set: flag.NewFlagSet("keygen", flag.ContinueOnError)}
    22  	cf.set.Usage = func() {}
    23  	cf.outPubPath = cf.set.String("out-pub", "", "Required: path to write the public key to")
    24  	cf.outKeyPath = cf.set.String("out-key", "", "Required: path to write the private key to")
    25  	cf.curve = cf.set.String("curve", "25519", "ECDH Curve (25519, P256)")
    26  	return &cf
    27  }
    28  
    29  func keygen(args []string, out io.Writer, errOut io.Writer) error {
    30  	cf := newKeygenFlags()
    31  	err := cf.set.Parse(args)
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	if err := mustFlagString("out-key", cf.outKeyPath); err != nil {
    37  		return err
    38  	}
    39  	if err := mustFlagString("out-pub", cf.outPubPath); err != nil {
    40  		return err
    41  	}
    42  
    43  	var pub, rawPriv []byte
    44  	var curve cert.Curve
    45  	switch *cf.curve {
    46  	case "25519", "X25519", "Curve25519", "CURVE25519":
    47  		pub, rawPriv = x25519Keypair()
    48  		curve = cert.Curve_CURVE25519
    49  	case "P256":
    50  		pub, rawPriv = p256Keypair()
    51  		curve = cert.Curve_P256
    52  	default:
    53  		return fmt.Errorf("invalid curve: %s", *cf.curve)
    54  	}
    55  
    56  	err = os.WriteFile(*cf.outKeyPath, cert.MarshalPrivateKey(curve, rawPriv), 0600)
    57  	if err != nil {
    58  		return fmt.Errorf("error while writing out-key: %s", err)
    59  	}
    60  
    61  	err = os.WriteFile(*cf.outPubPath, cert.MarshalPublicKey(curve, pub), 0600)
    62  	if err != nil {
    63  		return fmt.Errorf("error while writing out-pub: %s", err)
    64  	}
    65  
    66  	return nil
    67  }
    68  
    69  func keygenSummary() string {
    70  	return "keygen <flags>: create a public/private key pair. the public key can be passed to `nebula-cert sign`"
    71  }
    72  
    73  func keygenHelp(out io.Writer) {
    74  	cf := newKeygenFlags()
    75  	out.Write([]byte("Usage of " + os.Args[0] + " " + keygenSummary() + "\n"))
    76  	cf.set.SetOutput(out)
    77  	cf.set.PrintDefaults()
    78  }