forked from vulcand/vulcand
/
secret.go
107 lines (97 loc) · 2.53 KB
/
secret.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package command
import (
"fmt"
"io"
"os"
"github.com/mailgun/vulcand/Godeps/_workspace/src/github.com/codegangsta/cli"
"github.com/mailgun/vulcand/secret"
)
func NewKeyCommand(cmd *Command) cli.Command {
return cli.Command{
Name: "secret",
Usage: "Operations with vulcan encryption keys",
Subcommands: []cli.Command{
{
Name: "new_key",
Usage: "Generate new seal key",
Action: cmd.generateKeyAction,
Flags: []cli.Flag{
cli.StringFlag{Name: "file, f", Usage: "File to write to"},
},
},
{
Name: "seal_keypair",
Usage: "Seal key pair",
Action: cmd.sealKeyPairAction,
Flags: []cli.Flag{
cli.StringFlag{Name: "file, f", Usage: "File to write to"},
cli.StringFlag{Name: "sealKey", Usage: "Seal key - used to encrypt and seal certificate and private key"},
cli.StringFlag{Name: "privateKey", Usage: "Path to a private key"},
cli.StringFlag{Name: "cert", Usage: "Path to a certificate"},
},
},
},
}
}
func (cmd *Command) generateKeyAction(c *cli.Context) {
key, err := secret.NewKeyString()
if err != nil {
cmd.printError(fmt.Errorf("unable to generate key: %v", err))
return
}
stream, closer, err := getStream(c)
if err != nil {
cmd.printError(err)
return
}
if closer != nil {
defer closer.Close()
}
_, err = stream.Write([]byte(key))
if err != nil {
cmd.printError(fmt.Errorf("failed writing to output stream, error %s", err))
return
}
}
func (cmd *Command) sealKeyPairAction(c *cli.Context) {
// Read the key and get a box
box, err := readBox(c.String("sealKey"))
if err != nil {
cmd.printError(err)
return
}
// Read keyPairificate
stream, closer, err := getStream(c)
if err != nil {
cmd.printError(err)
return
}
if closer != nil {
defer closer.Close()
}
keyPair, err := readKeyPair(c.String("cert"), c.String("privateKey"))
if err != nil {
cmd.printError(fmt.Errorf("failed to read key pair: %s", err))
return
}
bytes, err := secret.SealKeyPairToJSON(box, keyPair)
if err != nil {
cmd.printError(fmt.Errorf("failed to seal key pair: %s", err))
return
}
_, err = stream.Write(bytes)
if err != nil {
cmd.printError(fmt.Errorf("failed writing to output stream, error %s", err))
return
}
}
func getStream(c *cli.Context) (io.Writer, io.Closer, error) {
if c.String("file") != "" {
file, err := os.OpenFile(c.String("file"), os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return nil, nil, fmt.Errorf("failed to open file %s, error: %s", c.String("file"), err)
}
return file, file, nil
}
return os.Stdout, nil, nil
}