| 1 |
package certificate |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/pem" |
| 5 |
"fmt" |
| 6 |
|
| 7 |
"github.com/smallstep/cli/flags" |
| 8 |
"github.com/smallstep/cli/ui" |
| 9 |
|
| 10 |
"github.com/smallstep/cli/command" |
| 11 |
"github.com/smallstep/cli/crypto/pemutil" |
| 12 |
"github.com/smallstep/cli/errs" |
| 13 |
"github.com/smallstep/cli/utils" |
| 14 |
"github.com/urfave/cli" |
| 15 |
) |
| 16 |
|
| 17 |
func keyCommand() cli.Command { |
| 18 |
return cli.Command{ |
| 19 |
Name: "key", |
| 20 |
Action: command.ActionFunc(keyAction), |
| 21 |
Usage: "print public key embedded in a certificate", |
| 22 |
UsageText: "**step certificate key** <crt-file> [**--out**=<file>]", |
| 23 |
Description: `**step certificate key** prints the public key embedded in a certificate or |
| 24 |
a certificate signing request. If <crt-file> is a certificate bundle, only the |
| 25 |
first block will be taken into account. |
| 26 |
|
| 27 |
The command will print a public or a decrypted private key if <crt-file> |
| 28 |
contains only a key. |
| 29 |
|
| 30 |
## POSITIONAL ARGUMENTS |
| 31 |
|
| 32 |
<crt-file> |
| 33 |
: Path to a certificate or certificate signing request (CSR). |
| 34 |
|
| 35 |
## EXAMPLES |
| 36 |
|
| 37 |
Get the public key of a certificate: |
| 38 |
''' |
| 39 |
$ step certificate key certificate.crt |
| 40 |
-----BEGIN PUBLIC KEY----- |
| 41 |
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEio9DLyuglMxakS3w00DUKdGbeXXB |
| 42 |
2Mfg6tVofeXYan9RbvftZufiypIAVqGZqO7CR9EbkoyHb/7GcKQa5HZ9rA== |
| 43 |
-----END PUBLIC KEY----- |
| 44 |
''' |
| 45 |
|
| 46 |
Get the public key of a CSR and save it to a file: |
| 47 |
''' |
| 48 |
$ step certificate key certificate.csr --out key.pem |
| 49 |
'''`, |
| 50 |
Flags: []cli.Flag{ |
| 51 |
cli.StringFlag{ |
| 52 |
Name: "out,output-file", |
| 53 |
Usage: "The destination <file> of the public key.", |
| 54 |
}, |
| 55 |
flags.Force, |
| 56 |
}, |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
func keyAction(ctx *cli.Context) error { |
| 61 |
if err := errs.NumberOfArguments(ctx, 1); err != nil { |
| 62 |
return err |
| 63 |
} |
| 64 |
|
| 65 |
filename := ctx.Args().Get(0) |
| 66 |
b, err := utils.ReadFile(filename) |
| 67 |
if err != nil { |
| 68 |
return err |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
key, err := pemutil.ParseKey(b, pemutil.WithFirstBlock()) |
| 73 |
if err != nil { |
| 74 |
return err |
| 75 |
} |
| 76 |
block, err := pemutil.Serialize(key) |
| 77 |
if err != nil { |
| 78 |
return err |
| 79 |
} |
| 80 |
|
| 81 |
if outputFile := ctx.String("output-file"); len(outputFile) > 0 { |
| 82 |
if err := utils.WriteFile(outputFile, pem.EncodeToMemory(block), 0600); err != nil { |
| 83 |
return err |
| 84 |
} |
| 85 |
ui.Printf("The public key has been saved in %s.\n", outputFile) |
| 86 |
return nil |
| 87 |
} |
| 88 |
|
| 89 |
fmt.Print(string(pem.EncodeToMemory(block))) |
| 90 |
return nil |
| 91 |
} |