forked from smallstep/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
key.go
91 lines (76 loc) · 2.17 KB
/
key.go
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
package certificate
import (
"encoding/pem"
"fmt"
"github.com/smallstep/cli/flags"
"github.com/smallstep/cli/ui"
"github.com/smallstep/cli/command"
"github.com/smallstep/cli/crypto/pemutil"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/utils"
"github.com/urfave/cli"
)
func keyCommand() cli.Command {
return cli.Command{
Name: "key",
Action: command.ActionFunc(keyAction),
Usage: "print public key embedded in a certificate",
UsageText: "**step certificate key** <crt-file> [**--out**=<file>]",
Description: `**step certificate key** prints the public key embedded in a certificate or
a certificate signing request. If <crt-file> is a certificate bundle, only the
first block will be taken into account.
The command will print a public or a decrypted private key if <crt-file>
contains only a key.
## POSITIONAL ARGUMENTS
<crt-file>
: Path to a certificate or certificate signing request (CSR).
## EXAMPLES
Get the public key of a certificate:
'''
$ step certificate key certificate.crt
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEio9DLyuglMxakS3w00DUKdGbeXXB
2Mfg6tVofeXYan9RbvftZufiypIAVqGZqO7CR9EbkoyHb/7GcKQa5HZ9rA==
-----END PUBLIC KEY-----
'''
Get the public key of a CSR and save it to a file:
'''
$ step certificate key certificate.csr --out key.pem
'''`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "out,output-file",
Usage: "The destination <file> of the public key.",
},
flags.Force,
},
}
}
func keyAction(ctx *cli.Context) error {
if err := errs.NumberOfArguments(ctx, 1); err != nil {
return err
}
filename := ctx.Args().Get(0)
b, err := utils.ReadFile(filename)
if err != nil {
return err
}
// Look only at the first block
key, err := pemutil.ParseKey(b, pemutil.WithFirstBlock())
if err != nil {
return err
}
block, err := pemutil.Serialize(key)
if err != nil {
return err
}
if outputFile := ctx.String("output-file"); len(outputFile) > 0 {
if err := utils.WriteFile(outputFile, pem.EncodeToMemory(block), 0600); err != nil {
return err
}
ui.Printf("The public key has been saved in %s.\n", outputFile)
return nil
}
fmt.Print(string(pem.EncodeToMemory(block)))
return nil
}