-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathtweakable_encryptor_test.go
309 lines (251 loc) · 8.19 KB
/
tweakable_encryptor_test.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package saltpack
import (
"bytes"
"crypto/sha512"
"fmt"
"io"
"golang.org/x/crypto/nacl/secretbox"
)
type testEncryptionOptions struct {
blockSize int
skipFooter bool
corruptEncryptionBlock func(bl *interface{}, ebn encryptionBlockNumber)
corruptCiphertextBeforeHash func(c []byte, ebn encryptionBlockNumber)
corruptPayloadNonce func(n Nonce, ebn encryptionBlockNumber) Nonce
corruptKeysNonce func(n Nonce, rid int) Nonce
corruptPayloadKey func(pk *[]byte, rid int)
corruptReceiverKeys func(rk *receiverKeys, rid int)
corruptSenderKeyPlaintext func(pk *[]byte)
corruptSenderKeyCiphertext func(pk []byte)
corruptHeader func(eh *EncryptionHeader)
corruptHeaderPacked func(b []byte)
}
func (eo testEncryptionOptions) getBlockSize() int {
if eo.blockSize == 0 {
return encryptionBlockSize
}
return eo.blockSize
}
type testEncryptStream struct {
version Version
output io.Writer
encoder encoder
payloadKey SymmetricKey
buffer bytes.Buffer
options testEncryptionOptions
headerHash headerHash
macKeys []macKey
numBlocks encryptionBlockNumber // the lower 64 bits of the nonce
err error
}
func (pes *testEncryptStream) Write(plaintext []byte) (int, error) {
if pes.err != nil {
return 0, pes.err
}
var ret int
if ret, pes.err = pes.buffer.Write(plaintext); pes.err != nil {
return 0, pes.err
}
// If es.buffer.Len() == encryptionBlockSize, we don't want to
// write it out just yet, since for V2 we need to be sure this
// isn't the last block.
for pes.buffer.Len() > pes.options.getBlockSize() {
pes.err = pes.encryptBlock(false)
if pes.err != nil {
return 0, pes.err
}
}
return ret, nil
}
func (pes *testEncryptStream) encryptBlock(isFinal bool) error {
plaintext := pes.buffer.Next(pes.options.getBlockSize())
checkEncryptBlockRead(pes.version, isFinal, pes.options.getBlockSize(), len(plaintext), pes.buffer.Len())
if err := pes.numBlocks.check(); err != nil {
return err
}
nonce := nonceForChunkSecretBox(pes.numBlocks)
if pes.options.corruptPayloadNonce != nil {
nonce = pes.options.corruptPayloadNonce(nonce, pes.numBlocks)
}
ciphertext := secretbox.Seal([]byte{}, plaintext, (*[24]byte)(&nonce), (*[32]byte)(&pes.payloadKey))
assertEncodedChunkState(pes.version, ciphertext, secretbox.Overhead, uint64(pes.numBlocks), isFinal)
if pes.options.corruptCiphertextBeforeHash != nil {
pes.options.corruptCiphertextBeforeHash(ciphertext, pes.numBlocks)
}
// Compute the digest to authenticate, and authenticate it for each
// recipient.
hashToAuthenticate := computePayloadHash(pes.version, pes.headerHash, nonce, ciphertext, isFinal)
var authenticators []payloadAuthenticator
for _, macKey := range pes.macKeys {
authenticator := computePayloadAuthenticator(macKey, hashToAuthenticate)
authenticators = append(authenticators, authenticator)
}
eBlock := makeEncryptionBlock(pes.version, ciphertext, authenticators, isFinal)
if pes.options.corruptEncryptionBlock != nil {
pes.options.corruptEncryptionBlock(&eBlock, pes.numBlocks)
}
if err := pes.encoder.Encode(eBlock); err != nil {
return err
}
pes.numBlocks++
return nil
}
func (pes *testEncryptStream) init(
version Version, sender BoxSecretKey, receivers []BoxPublicKey,
ephemeralKeyCreator EphemeralKeyCreator, rng encryptRNG) error {
if err := checkKnownVersion(version); err != nil {
return err
}
if err := checkEncryptReceivers(receivers); err != nil {
return err
}
receivers, err := rng.shuffleReceivers(receivers)
if err != nil {
return err
}
ephemeralKey, err := ephemeralKeyCreator.CreateEphemeralKey()
if err != nil {
return err
}
// If we have a NULL Sender key, then we really want an ephemeral key
// as the main encryption key.
if sender == nil {
sender = ephemeralKey
}
eh := EncryptionHeader{
FormatName: FormatName,
Version: version,
Type: MessageTypeEncryption,
Ephemeral: ephemeralKey.GetPublicKey().ToKID(),
Receivers: make([]receiverKeys, 0, len(receivers)),
}
payloadKey, err := rng.createSymmetricKey()
if err != nil {
return err
}
pes.payloadKey = *payloadKey
senderPlaintext := sliceToByte32(sender.GetPublicKey().ToKID())
senderPlaintextSlice := senderPlaintext[:]
if pes.options.corruptSenderKeyPlaintext != nil {
pes.options.corruptSenderKeyPlaintext(&senderPlaintextSlice)
}
nonce := nonceForSenderKeySecretBox()
eh.SenderSecretbox = secretbox.Seal([]byte{}, senderPlaintextSlice, (*[24]byte)(&nonce), (*[32]byte)(&pes.payloadKey))
if pes.options.corruptSenderKeyCiphertext != nil {
pes.options.corruptSenderKeyCiphertext(eh.SenderSecretbox)
}
for rid, receiver := range receivers {
payloadKeySlice := pes.payloadKey[:]
if pes.options.corruptPayloadKey != nil {
pes.options.corruptPayloadKey(&payloadKeySlice, rid)
}
nonceTmp := nonceForPayloadKeyBox(version, uint64(rid))
if pes.options.corruptKeysNonce != nil {
nonceTmp = pes.options.corruptKeysNonce(nonceTmp, rid)
}
payloadKeyBox := ephemeralKey.Box(receiver, nonceTmp, payloadKeySlice)
keys := receiverKeys{
PayloadKeyBox: payloadKeyBox,
}
// Don't specify the receivers if this public key wants to hide
if !receiver.HideIdentity() {
keys.ReceiverKID = receiver.ToKID()
}
if pes.options.corruptReceiverKeys != nil {
pes.options.corruptReceiverKeys(&keys, rid)
}
eh.Receivers = append(eh.Receivers, keys)
}
if pes.options.corruptHeader != nil {
pes.options.corruptHeader(&eh)
}
// Encode the header and the header length, and write them out immediately.
headerBytes, err := encodeToBytes(eh)
if err != nil {
return err
}
if pes.options.corruptHeaderPacked != nil {
pes.options.corruptHeaderPacked(headerBytes)
}
pes.headerHash = sha512.Sum512(headerBytes)
err = pes.encoder.Encode(headerBytes)
if err != nil {
return err
}
// Use the header hash to compute the MAC keys.
//
// TODO: Plumb the pre-computed shared keys above through to
// computeMACKeysSender.
pes.macKeys = computeMACKeysSender(version, sender, ephemeralKey, receivers, pes.headerHash)
return nil
}
func (pes *testEncryptStream) Close() error {
switch pes.version {
case Version1():
if pes.buffer.Len() > 0 {
err := pes.encryptBlock(false)
if err != nil {
return err
}
}
if pes.buffer.Len() > 0 {
panic(fmt.Sprintf("es.buffer.Len()=%d > 0", pes.buffer.Len()))
}
if pes.options.skipFooter {
return nil
}
return pes.encryptBlock(true)
case Version2():
isFinal := true
if pes.options.skipFooter {
isFinal = false
}
err := pes.encryptBlock(isFinal)
if err != nil {
return err
}
if pes.buffer.Len() > 0 {
panic(fmt.Sprintf("pes.buffer.Len()=%d > 0", pes.buffer.Len()))
}
return nil
default:
panic(ErrBadVersion{pes.version})
}
}
// noShuffleRNG implements encryptRNG to not shuffle. All of the tests
// above no shuffling.
type noShuffleRNG struct{}
func (noShuffleRNG) createSymmetricKey() (*SymmetricKey, error) {
return newRandomSymmetricKey()
}
func (noShuffleRNG) shuffleReceivers(receivers []BoxPublicKey) ([]BoxPublicKey, error) {
return receivers, nil
}
// Options are available mainly for testing. Can't think of a good reason for
// end-users to have to specify options.
func newTestEncryptStream(version Version, ciphertext io.Writer, sender BoxSecretKey, receivers []BoxPublicKey, ephemeralKeyCreator EphemeralKeyCreator, options testEncryptionOptions) (io.WriteCloser, error) {
pes := &testEncryptStream{
version: version,
output: ciphertext,
encoder: newEncoder(ciphertext),
options: options,
}
err := pes.init(version, sender, receivers, ephemeralKeyCreator, noShuffleRNG{})
return pes, err
}
func testSeal(version Version, plaintext []byte, sender BoxSecretKey, receivers []BoxPublicKey, options testEncryptionOptions) (out []byte, err error) {
var buf bytes.Buffer
es, err := newTestEncryptStream(version, &buf, sender, receivers, ephemeralKeyCreator{}, options)
if err != nil {
return nil, err
}
if _, err := es.Write(plaintext); err != nil {
return nil, err
}
if err := es.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}