| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | |
| 8 | "github.com/spf13/cobra" |
| 9 | "golang.org/x/mod/sumdb/note" |
| 10 | ) |
| 11 | |
| 12 | func genkeyCmd() *cobra.Command { |
| 13 | var ( |
| 14 | name string |
| 15 | out string |
| 16 | ) |
| 17 | |
| 18 | cmd := &cobra.Command{ |
| 19 | Use: "genkey", |
| 20 | Short: "Generate an Ed25519 signing key for the sumdb", |
| 21 | RunE: func(cmd *cobra.Command, args []string) error { |
| 22 | return runGenkey(name, out) |
| 23 | }, |
| 24 | } |
| 25 | |
| 26 | cmd.Flags().StringVarP(&name, "name", "n", "go.example.com", "server name for the signing key") |
| 27 | cmd.Flags().StringVarP(&out, "out", "o", "", "write private key to file (default: stdout)") |
| 28 | |
| 29 | return cmd |
| 30 | } |
| 31 | |
| 32 | func runGenkey(name, out string) error { |
| 33 | skey, vkey, err := note.GenerateKey(rand.Reader, name) |
| 34 | if err != nil { |
| 35 | return fmt.Errorf("generate key: %w", err) |
| 36 | } |
| 37 | |
| 38 | if out != "" { |
| 39 | if err := os.WriteFile(out, []byte(skey+"\n"), 0o600); err != nil { |
| 40 | return fmt.Errorf("write key: %w", err) |
| 41 | } |
| 42 | fmt.Fprintf(os.Stderr, "private key written to %s\n", out) |
| 43 | } else { |
| 44 | fmt.Println(skey) |
| 45 | } |
| 46 | |
| 47 | fmt.Fprintf(os.Stderr, "public key (verifier):\n%s\n", vkey) |
| 48 | return nil |
| 49 | } |
| 50 | |