| 1 | package key |
| 2 | |
| 3 | import ( |
| 4 | "crypto" |
| 5 | "encoding/pem" |
| 6 | "os" |
| 7 | |
| 8 | "github.com/pkg/errors" |
| 9 | "github.com/smallstep/cli/command" |
| 10 | "github.com/smallstep/cli/crypto/pemutil" |
| 11 | "github.com/smallstep/cli/errs" |
| 12 | "github.com/smallstep/cli/flags" |
| 13 | "github.com/smallstep/cli/ui" |
| 14 | "github.com/smallstep/cli/utils" |
| 15 | "github.com/urfave/cli" |
| 16 | ) |
| 17 | |
| 18 | func publicCommand() cli.Command { |
| 19 | return cli.Command{ |
| 20 | Name: "public", |
| 21 | Action: command.ActionFunc(publicAction), |
| 22 | Usage: `print the public key from a private key`, |
| 23 | UsageText: `**step crypto key public** <key-file> [**--out**=<path>]`, |
| 24 | Description: `**step crypto key public** prints or writes in a PEM format |
| 25 | the public key corresponding to the given <key-file>. |
| 26 | |
| 27 | ## POSITIONAL ARGUMENTS |
| 28 | |
| 29 | <key-file> |
| 30 | : Path to a private key. |
| 31 | |
| 32 | ## EXAMPLES |
| 33 | |
| 34 | Print the corresponding public key: |
| 35 | ''' |
| 36 | $ step crypto key public priv.pem |
| 37 | ''' |
| 38 | |
| 39 | Write the corresponding public key to a file: |
| 40 | ''' |
| 41 | $ step crypto key public --out pub.pem key.pem |
| 42 | '''`, |
| 43 | Flags: []cli.Flag{ |
| 44 | cli.StringFlag{ |
| 45 | Name: "out", |
| 46 | Usage: "Path to write the public key.", |
| 47 | }, |
| 48 | flags.Force, |
| 49 | }, |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | func publicAction(ctx *cli.Context) error { |
| 54 | if err := errs.MinMaxNumberOfArguments(ctx, 0, 1); err != nil { |
| 55 | return err |
| 56 | } |
| 57 | |
| 58 | var name string |
| 59 | switch ctx.NArg() { |
| 60 | case 0: |
| 61 | name = "-" |
| 62 | case 1: |
| 63 | name = ctx.Args().First() |
| 64 | default: |
| 65 | return errs.TooManyArguments(ctx) |
| 66 | } |
| 67 | |
| 68 | b, err := utils.ReadFile(name) |
| 69 | if err != nil { |
| 70 | return err |
| 71 | } |
| 72 | |
| 73 | priv, err := pemutil.Parse(b) |
| 74 | if err != nil { |
| 75 | return err |
| 76 | } |
| 77 | |
| 78 | pub, ok := priv.(interface{ Public() crypto.PublicKey }) |
| 79 | if !ok { |
| 80 | return errors.Errorf("cannot get a public key from %s", name) |
| 81 | } |
| 82 | |
| 83 | if out := ctx.String("out"); out == "" { |
| 84 | block, err := pemutil.Serialize(pub.Public()) |
| 85 | if err != nil { |
| 86 | return err |
| 87 | } |
| 88 | os.Stdout.Write(pem.EncodeToMemory(block)) |
| 89 | } else { |
| 90 | _, err = pemutil.Serialize(pub.Public(), pemutil.ToFile(out, 0600)) |
| 91 | if err != nil { |
| 92 | return err |
| 93 | } |
| 94 | ui.Printf("Your key has been saved in %s.\n", out) |
| 95 | } |
| 96 | |
| 97 | return nil |
| 98 | } |