File: public.go

package info (click to toggle)
golang-github-smallstep-cli 0.15.16%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,404 kB
  • sloc: sh: 512; makefile: 99
file content (98 lines) | stat: -rw-r--r-- 1,996 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package key

import (
	"crypto"
	"encoding/pem"
	"os"

	"github.com/pkg/errors"
	"github.com/smallstep/cli/command"
	"github.com/smallstep/cli/crypto/pemutil"
	"github.com/smallstep/cli/errs"
	"github.com/smallstep/cli/flags"
	"github.com/smallstep/cli/ui"
	"github.com/smallstep/cli/utils"
	"github.com/urfave/cli"
)

func publicCommand() cli.Command {
	return cli.Command{
		Name:      "public",
		Action:    command.ActionFunc(publicAction),
		Usage:     `print the public key from a private key`,
		UsageText: `**step crypto key public** <key-file> [**--out**=<path>]`,
		Description: `**step crypto key public** prints or writes in a PEM format
the public key corresponding to the given <key-file>.

## POSITIONAL ARGUMENTS

<key-file>
:  Path to a private key.

## EXAMPLES

Print the corresponding public key:
'''
$ step crypto key public priv.pem
'''

Write the corresponding public key to a file:
'''
$ step crypto key public --out pub.pem key.pem
'''`,
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:  "out",
				Usage: "Path to write the public key.",
			},
			flags.Force,
		},
	}
}

func publicAction(ctx *cli.Context) error {
	if err := errs.MinMaxNumberOfArguments(ctx, 0, 1); err != nil {
		return err
	}

	var name string
	switch ctx.NArg() {
	case 0:
		name = "-"
	case 1:
		name = ctx.Args().First()
	default:
		return errs.TooManyArguments(ctx)
	}

	b, err := utils.ReadFile(name)
	if err != nil {
		return err
	}

	priv, err := pemutil.Parse(b)
	if err != nil {
		return err
	}

	pub, ok := priv.(interface{ Public() crypto.PublicKey })
	if !ok {
		return errors.Errorf("cannot get a public key from %s", name)
	}

	if out := ctx.String("out"); out == "" {
		block, err := pemutil.Serialize(pub.Public())
		if err != nil {
			return err
		}
		os.Stdout.Write(pem.EncodeToMemory(block))
	} else {
		_, err = pemutil.Serialize(pub.Public(), pemutil.ToFile(out, 0600))
		if err != nil {
			return err
		}
		ui.Printf("Your key has been saved in %s.\n", out)
	}

	return nil
}