Debian Codegraph @

command/crypto/nacl/secretbox.go

raw symbols SCIP
1 package nacl
2
3 import (
4 "fmt"
5 "io/ioutil"
6 "os"
7
8 "github.com/pkg/errors"
9 "github.com/smallstep/cli/errs"
10 "github.com/smallstep/cli/utils"
11 "github.com/urfave/cli"
12 "golang.org/x/crypto/nacl/secretbox"
13 )
14
15 func secretboxCommand() cli.Command {
16 return cli.Command{
17 Name: "secretbox",
18 Usage: "encrypt and authenticate small messages using secret-key cryptography",
19 UsageText: "step crypto nacl secretbox <subcommand> [arguments] [global-flags] [subcommand-flags]",
20 Description: `**step crypto nacl secretbox** command group uses secret-key cryptography to
21 encrypt, decrypt and authenticate messages. The implementation is based on NaCl's
22 crypto_secretbox function.
23
24 NaCl crypto_secretbox is designed to meet the standard notions of privacy and
25 authenticity for a secret-key authenticated-encryption scheme using nonces. For
26 formal definitions see, e.g., Bellare and Namprempre, "Authenticated encryption:
27 relations among notions and analysis of the generic composition paradigm,"
28 Lecture Notes in Computer Science 1976 (2000), 531–545,
29 http://www-cse.ucsd.edu/~mihir/papers/oem.html. Note that the length is not
30 hidden. Note also that it is the caller's responsibility to ensure the
31 uniqueness of nonces—for example, by using nonce 1 for the first message, nonce
32 2 for the second message, etc. Nonces are long enough that randomly generated
33 nonces have negligible risk of collision.
34
35 By default nonces are alphanumeric, but it's possible to use binary nonces using
36 the prefix 'base64:' and the standard base64 encoding of the data, e.g.
37 'base64:081D3pFPBkwx1bURR9HQjiYbAUxigo0Z'. The prefix 'string:' is also
38 accepted, but it will be equivalent to not using a prefix. Nonces cannot be
39 longer than 24 bytes.
40
41 NaCl crypto_secretbox is crypto_secretbox_xsalsa20poly1305, a particular
42 combination of Salsa20 and Poly1305 specified in "Cryptography in NaCl". This
43 function is conjectured to meet the standard notions of privacy and
44 authenticity.
45
46 These commands are interoperable with NaCl: https://nacl.cr.yp.to/secretbox.html
47
48 ## EXAMPLES
49
50 Encrypt a message using a 256-bit secret key, a new nacl box private key can
51 be used as the secret:
52 '''
53 $ step crypto nacl secretbox seal nonce secretbox.key
54 Please enter text to seal: ********
55 o2NJTsIJsk0dl4epiBwS1mM4xFED7iE
56
57 $ cat message.txt | step crypto nacl secretbox seal nonce secretbox.key
58 o2NJTsIJsk0dl4epiBwS1mM4xFED7iE
59 '''
60
61 Encrypt the message using a base64 nonce:
62 '''
63 $ cat message.txt | step crypto nacl secretbox seal base64:bm9uY2U= secretbox.key
64 o2NJTsIJsk0dl4epiBwS1mM4xFED7iE
65 '''
66
67 Decrypt and authenticate the message:
68 '''
69 $ echo o2NJTsIJsk0dl4epiBwS1mM4xFED7iE | step crypto nacl secretbox open nonce secretbox.key
70 message
71 '''`,
72 Subcommands: cli.Commands{
73 secretboxOpenCommand(),
74 secretboxSealCommand(),
75 },
76 }
77 }
78
79 func secretboxOpenCommand() cli.Command {
80 return cli.Command{
81 Name: "open",
82 Action: cli.ActionFunc(secretboxOpenAction),
83 Usage: "authenticate and decrypt a box produced by seal",
84 UsageText: `**step crypto nacl secretbox open** <nonce> <key-file>
85 [--raw]`,
86 Description: `**step crypto nacl secretbox open** verifies and decrypts a ciphertext using a
87 secret key and a nonce.
88
89 This command uses an implementation of NaCl's crypto_secretbox_open function.
90
91 For examples, see **step help crypto nacl secretbox**.
92
93 ## POSITIONAL ARGUMENTS
94
95 <nonce>
96 : The nonce provided when the secretbox was sealed.
97
98 : To use a binary nonce use the prefix 'base64:' and the standard base64
99 encoding. e.g. base64:081D3pFPBkwx1bURR9HQjiYbAUxigo0Z
100
101 <key-file>
102 : The path to the shared key.`,
103 Flags: []cli.Flag{
104 cli.BoolFlag{
105 Name: "raw",
106 Usage: "Indicates that input is not base64 encoded",
107 },
108 },
109 }
110 }
111
112 func secretboxSealCommand() cli.Command {
113 return cli.Command{
114 Name: "seal",
115 Action: cli.ActionFunc(secretboxSealAction),
116 Usage: "produce an encrypted ciphertext",
117 UsageText: `**step crypto nacl secretbox seal** <nonce> <key-file>
118 [--raw]`,
119 Description: `**step crypto nacl secretbox seal** encrypts and authenticates a message using
120 a secret key and a nonce.
121
122 This command uses an implementation of NaCl's crypto_secretbox function.
123
124 For examples, see **step help crypto nacl secretbox**.
125
126 ## POSITIONAL ARGUMENTS
127
128 <nonce>
129 : Must be unique for each distinct message for a given key.
130
131 : To use a binary nonce use the prefix 'base64:' and the standard base64
132 encoding. e.g. base64:081D3pFPBkwx1bURR9HQjiYbAUxigo0Z
133
134 <key-file>
135 : The path to the shared key.`,
136 Flags: []cli.Flag{
137 cli.BoolFlag{
138 Name: "raw",
139 Usage: "Do not base64 encode output",
140 },
141 },
142 }
143 }
144
145 func secretboxOpenAction(ctx *cli.Context) error {
146 if err := errs.NumberOfArguments(ctx, 2); err != nil {
147 return err
148 }
149
150 args := ctx.Args()
151 nonce, err := decodeNonce(args[0])
152 if err != nil {
153 return err
154 }
155 keyFile := args[1]
156
157 if len(nonce) > 24 {
158 return errors.New("nonce cannot be longer than 24 bytes")
159 }
160
161 key, err := ioutil.ReadFile(keyFile)
162 if err != nil {
163 return errs.FileError(err, keyFile)
164 } else if len(key) != 32 {
165 return errors.New("invalid key file: key size is not 32 bytes")
166 }
167
168 input, err := utils.ReadAll(os.Stdin)
169 if err != nil {
170 return errors.Wrap(err, "error reading input")
171 }
172
173 var rawInput []byte
174 if ctx.Bool("raw") {
175 rawInput = input
176 } else {
177 // DecodeLen returns the maximum length,
178 // Decode will return the actual length.
179 rawInput = make([]byte, b64Encoder.DecodedLen(len(input)))
180 n, err := b64Encoder.Decode(rawInput, input)
181 if err != nil {
182 return errors.Wrap(err, "error decoding base64 input")
183 }
184 rawInput = rawInput[:n]
185 }
186
187 var n [24]byte
188 var k [32]byte
189 copy(n[:], nonce)
190 copy(k[:], key)
191
192 // Fixme: if we prepend the nonce in the seal we can use use rawInput[24:]
193 // as the message and rawInput[:24] as the nonce instead of requiring one.
194 raw, ok := secretbox.Open(nil, rawInput, &n, &k)
195 if !ok {
196 return errors.New("error authenticating or decrypting input")
197 }
198
199 os.Stdout.Write(raw)
200 return nil
201 }
202
203 func secretboxSealAction(ctx *cli.Context) error {
204 if err := errs.NumberOfArguments(ctx, 2); err != nil {
205 return err
206 }
207
208 args := ctx.Args()
209 nonce, err := decodeNonce(args[0])
210 if err != nil {
211 return err
212 }
213 keyFile := args[1]
214
215 if len(nonce) > 24 {
216 return errors.New("nonce cannot be longer than 24 bytes")
217 }
218
219 key, err := ioutil.ReadFile(keyFile)
220 if err != nil {
221 return errs.FileError(err, keyFile)
222 } else if len(key) != 32 {
223 return errors.New("invalid key: key size is not 32 bytes")
224 }
225
226 input, err := utils.ReadInput("Please enter text to seal")
227 if err != nil {
228 return errors.Wrap(err, "error reading input")
229 }
230
231 var n [24]byte
232 var k [32]byte
233 copy(n[:], nonce)
234 copy(k[:], key)
235
236 // Fixme: we can prepend nonce[:] so it's not necessary in the open.
237 raw := secretbox.Seal(nil, input, &n, &k)
238 if ctx.Bool("raw") {
239 os.Stdout.Write(raw)
240 } else {
241 fmt.Println(b64Encoder.EncodeToString(raw))
242 }
243
244 return nil
245 }