forked from smallstep/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
box.go
274 lines (225 loc) 路 6.96 KB
/
box.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package nacl
import (
"crypto/rand"
"fmt"
"io/ioutil"
"os"
"github.com/pkg/errors"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/utils"
"github.com/urfave/cli"
"golang.org/x/crypto/nacl/box"
)
func boxCommand() cli.Command {
return cli.Command{
Name: "box",
Usage: "authenticate and encrypt small messages using public-key cryptography",
UsageText: "step crypto nacl box <subcommand> [arguments] [global-flags] [subcommand-flags]",
Description: `**step crypto nacl box** command group uses public-key cryptography to
encrypt, decrypt and authenticate messages.
## EXAMPLES
Create a keypair for encrypting/decrypting messages:
'''
# Bob
$ step crypto nacl box keypair bob.box.pub bob.box.priv
# Alice
$ step crypto nacl box keypair alice.box.pub alice.box.priv
'''
Bob encrypts a message for Alice using her public key and signs it using his
private key:
'''
$ echo message | step crypto nacl box seal nonce alice.box.pub bob.box.priv
0oM0A6xIezA6iMYssZECmbMRQh77mzDt
'''
Alice receives the encrypted message and the nonce and decrypts with her
private key and validates the message from Bob using his public key:
'''
$ echo 0oM0A6xIezA6iMYssZECmbMRQh77mzDt | step crypto nacl box open nonce bob.box.pub alice.box.priv
message
'''`,
Subcommands: cli.Commands{
boxKeypairCommand(),
boxOpenCommand(),
boxSealCommand(),
},
}
}
func boxKeypairCommand() cli.Command {
return cli.Command{
Name: "keypair",
Action: cli.ActionFunc(boxKeypairAction),
Usage: "generate a key for use with seal and open",
UsageText: "**step crypto nacl box keypair** <pub-file> <priv-file>",
Description: `Generates a new public/private keypair suitable for use with seal and open.
The private key is encrypted using a password in a nacl secretbox.
For examples, see **step help crypto nacl box**.
## POSITIONAL ARGUMENTS
<pub-file>
: The path to write the public key.
<priv-file>
: The path to write the encrypted private key.`,
}
}
func boxOpenCommand() cli.Command {
return cli.Command{
Name: "open",
Action: cli.ActionFunc(boxOpenAction),
Usage: "authenticate and decrypt a box produced by seal",
UsageText: `**step crypto nacl box open** <nonce> <sender-pub-key> <priv-key>
[--raw]`,
Description: `Authenticate and decrypt a box produced by seal using the specified KEY. If
PRIV_KEY is encrypted you will be prompted for the password. The sealed box is
read from STDIN and the decrypted plaintext is written to STDOUT.
For examples, see **step help crypto nacl box**.
## POSITIONAL ARGUMENTS
<nonce>
: The nonce provided when the box was sealed.
<sender-pub-key>
: The path to the public key of the peer that produced the sealed box.
<priv-key>
: The path to the private key used to open the box.`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "raw",
Usage: "Indicates that input is not base64 encoded",
},
},
}
}
func boxSealCommand() cli.Command {
return cli.Command{
Name: "seal",
Action: cli.ActionFunc(boxSealAction),
Usage: "produce an authenticated and encrypted ciphertext",
UsageText: `**step crypto nacl box seal** <nonce> <recipient-pub-key> <priv-key>
[--raw]`,
Description: `Reads plaintext from STDIN and writes an encrypted and authenticated
ciphertext to STDOUT. The "box" can be open by the a recipient who has access
to the private key corresponding to <recipient-pub-key>.
## POSITIONAL ARGUMENTS
<nonce>
: Must be unique for each distinct message for a given pair of keys.
<recipient-pub-key>
: The path to the public key of the intended recipient of the sealed box.
<priv-key>
: The path to the private key used for authentication.`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "raw",
Usage: "Do not base64 encode output",
},
},
}
}
func boxKeypairAction(ctx *cli.Context) error {
if err := errs.NumberOfArguments(ctx, 2); err != nil {
return err
}
args := ctx.Args()
pubFile, privFile := args[0], args[1]
if pubFile == privFile {
return errs.EqualArguments(ctx, "<pub-file>", "<priv-file>")
}
pub, priv, err := box.GenerateKey(rand.Reader)
if err != nil {
return errors.Wrap(err, "error generating key")
}
if err := utils.WriteFile(pubFile, pub[:], 0600); err != nil {
return errs.FileError(err, pubFile)
}
if err := utils.WriteFile(privFile, priv[:], 0600); err != nil {
return errs.FileError(err, privFile)
}
return nil
}
func boxOpenAction(ctx *cli.Context) error {
if err := errs.NumberOfArguments(ctx, 3); err != nil {
return err
}
args := ctx.Args()
nonce, pubFile, privFile := []byte(args[0]), args[1], args[2]
if len(nonce) > 24 {
return errors.New("nonce cannot be longer than 24 bytes")
}
pub, err := ioutil.ReadFile(pubFile)
if err != nil {
return errs.FileError(err, pubFile)
} else if len(pub) != 32 {
return errors.New("invalid public key: key size is not 32 bytes")
}
priv, err := ioutil.ReadFile(privFile)
if err != nil {
return errs.FileError(err, privFile)
} else if len(priv) != 32 {
return errors.New("invalid private key: key size is not 32 bytes")
}
input, err := utils.ReadAll(os.Stdin)
if err != nil {
return errs.Wrap(err, "error reading input")
}
var rawInput []byte
if ctx.Bool("raw") {
rawInput = input
} else {
// DecodeLen returns the maximum length,
// Decode will return the actual length.
rawInput = make([]byte, b64Encoder.DecodedLen(len(input)))
n, err := b64Encoder.Decode(rawInput, input)
if err != nil {
return errors.Wrap(err, "error decoding base64 input")
}
rawInput = rawInput[:n]
}
var n [24]byte
var pb, pv [32]byte
copy(n[:], nonce)
copy(pb[:], pub)
copy(pv[:], priv)
// Fixme: if we prepend the nonce in the seal we can use use rawInput[24:]
// as the message and rawInput[:24] as the nonce instead of requiring one.
raw, ok := box.Open(nil, rawInput, &n, &pb, &pv)
if !ok {
return errors.New("error authenticating or decrypting input")
}
os.Stdout.Write(raw)
return nil
}
func boxSealAction(ctx *cli.Context) error {
if err := errs.NumberOfArguments(ctx, 3); err != nil {
return err
}
args := ctx.Args()
nonce, pubFile, privFile := []byte(args[0]), args[1], args[2]
if len(nonce) > 24 {
return errors.New("nonce cannot be longer than 24 bytes")
}
pub, err := ioutil.ReadFile(pubFile)
if err != nil {
return errs.FileError(err, pubFile)
} else if len(pub) != 32 {
return errors.New("invalid public key: key size is not 32 bytes")
}
priv, err := ioutil.ReadFile(privFile)
if err != nil {
return errs.FileError(err, privFile)
} else if len(priv) != 32 {
return errors.New("invalid private key: key size is not 32 bytes")
}
input, err := utils.ReadInput("Write text to seal: ")
if err != nil {
return errors.Wrap(err, "error reading input")
}
var n [24]byte
var pb, pv [32]byte
copy(n[:], nonce)
copy(pb[:], pub)
copy(pv[:], priv)
// Fixme: we can prepend nonce[:] so it's not necessary in the open.
raw := box.Seal(nil, input, &n, &pb, &pv)
if ctx.Bool("raw") {
os.Stdout.Write(raw)
} else {
fmt.Println(b64Encoder.EncodeToString(raw))
}
return nil
}