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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use crate::crypto::aesgcm::{AesGcm256, ConstantTimeEq, Tag, TAG_LENGTH};
use crate::crypto::ecc::{retrieve_key, store_key_for_multi_recipients, MultiRecipientPersistent};

use crate::layers::traits::{LayerFailSafeReader, LayerReader, LayerWriter};
use crate::Error;
use std::io;
use std::io::{BufReader, Cursor, Read, Seek, SeekFrom, Write};

use crate::config::{ArchiveReaderConfig, ArchiveWriterConfig};
use crate::errors::ConfigError;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaChaRng;
use x25519_dalek::{PublicKey, StaticSecret};

use serde::{Deserialize, Serialize};

const CIPHER_BUF_SIZE: u64 = 4096;
const KEY_SIZE: usize = 32;
// This is the size of the nonce taken as input
const NONCE_SIZE: usize = 8;
const CHUNK_SIZE: u64 = 128 * 1024;

// This is the Nonce as expected by AesGcm
const NONCE_AES_SIZE: usize = 96 / 8;
type Nonce = [u8; NONCE_AES_SIZE];

/// Build nonce according to a given state
///
/// AesGcm expect a 96 bits nonce.
/// The nonce build as:
/// {
///   - 8 byte nonce, unique per archive
///   - 4 byte counter, unique per chunk and incremental
/// }
///
/// Inspired from the construction in TLS or STREAM from "Online
/// Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance"
fn build_nonce(nonce_prefix: [u8; NONCE_SIZE], current_ctr: u32) -> Nonce {
    let mut nonce = [0u8; NONCE_AES_SIZE];
    nonce[..NONCE_SIZE].copy_from_slice(&nonce_prefix);
    nonce[NONCE_SIZE..].copy_from_slice(&current_ctr.to_be_bytes());
    nonce
}

// ---------- Config ----------

/// Configuration stored in the header, to be reloaded
#[derive(Serialize, Deserialize)]
pub struct EncryptionPersistentConfig {
    pub multi_recipient: MultiRecipientPersistent,
    nonce: [u8; NONCE_SIZE],
}

pub struct EncryptionConfig {
    /// Public keys with which to encrypt the symmetric encryption key below
    ecc_keys: Vec<PublicKey>,
    /// Symmetric encryption Key
    key: [u8; KEY_SIZE],
    /// Symmetric encryption nonce
    nonce: [u8; NONCE_SIZE],
}

impl std::default::Default for EncryptionConfig {
    fn default() -> Self {
        // Use OsRng from crate rand, that uses getrandom() from crate getrandom.
        // getrandom provides implementations for many systems, listed on
        // https://docs.rs/getrandom/0.1.14/getrandom/
        // On Linux it uses `getrandom()` syscall and falls back on `/dev/urandom`.
        // On Windows it uses `RtlGenRandom` API (available since Windows XP/Windows Server 2003).
        //
        // So this seems to be secure, but unfortunately there is no strong
        // warranty that this would stay this way forever.
        // In order to be "better safe than sorry", seed `ChaChaRng` from the
        // bytes generated by `OsRng` in order to build a CSPRNG
        // (Cryptographically Secure PseudoRandom Number Generator).
        // This is actually what `ChaChaRng::from_entropy()` does:
        // https://github.com/rust-random/rand/blob/rand_core-0.5.1/rand_core/src/lib.rs#L378
        // and this function is documented as "secure" in
        // https://docs.rs/rand/0.7.3/rand/trait.SeedableRng.html#method.from_entropy
        let mut csprng = ChaChaRng::from_entropy();
        let key = csprng.gen::<[u8; KEY_SIZE]>();
        let nonce = csprng.gen::<[u8; NONCE_SIZE]>();
        EncryptionConfig {
            ecc_keys: Vec::new(),
            key,
            nonce,
        }
    }
}

impl EncryptionConfig {
    /// Consistency check
    pub fn check(&self) -> Result<(), ConfigError> {
        if self.ecc_keys.is_empty() {
            Err(ConfigError::EncryptionKeyIsMissing)
        } else {
            Ok(())
        }
    }

    pub fn to_persistent(&self) -> Result<EncryptionPersistentConfig, ConfigError> {
        let mut rng = ChaChaRng::from_entropy();
        if let Ok(multi_recipient) =
            store_key_for_multi_recipients(&self.ecc_keys, &self.key, &mut rng)
        {
            Ok(EncryptionPersistentConfig {
                multi_recipient,
                nonce: self.nonce,
            })
        } else {
            Err(ConfigError::ECIESComputationError)
        }
    }
}

impl ArchiveWriterConfig {
    /// Set public keys to use
    pub fn add_public_keys(&mut self, keys: &[PublicKey]) -> &mut ArchiveWriterConfig {
        self.encrypt.ecc_keys.extend_from_slice(keys);
        self
    }

    /// Return the key used for encryption
    pub fn encryption_key(&self) -> &[u8; KEY_SIZE] {
        &self.encrypt.key
    }

    /// Return the nonce used for encryption
    pub fn encryption_nonce(&self) -> &[u8; NONCE_SIZE] {
        &self.encrypt.nonce
    }
}

pub struct EncryptionReaderConfig {
    /// Private key(s) to use
    private_keys: Vec<StaticSecret>,
    /// Symmetric encryption key and nonce, if decrypted successfully from header
    encrypt_parameters: Option<([u8; KEY_SIZE], [u8; NONCE_SIZE])>,
}

impl std::default::Default for EncryptionReaderConfig {
    fn default() -> Self {
        Self {
            private_keys: Vec::new(),
            encrypt_parameters: None,
        }
    }
}

impl EncryptionReaderConfig {
    pub fn load_persistent(
        &mut self,
        config: EncryptionPersistentConfig,
    ) -> Result<(), ConfigError> {
        if self.private_keys.is_empty() {
            return Err(ConfigError::PrivateKeyNotSet);
        }
        for private_key in &self.private_keys {
            match retrieve_key(&config.multi_recipient, private_key) {
                Ok(Some(key)) => {
                    self.encrypt_parameters = Some((key, config.nonce));
                    break;
                }
                _ => {
                    continue;
                }
            };
        }

        if self.encrypt_parameters.is_none() {
            return Err(ConfigError::PrivateKeyNotFound);
        }
        Ok(())
    }
}

impl ArchiveReaderConfig {
    /// Set private key to use
    pub fn add_private_keys(&mut self, keys: &[StaticSecret]) -> &mut ArchiveReaderConfig {
        self.encrypt.private_keys.extend_from_slice(keys);
        self
    }

    /// Retrieve key and nonce used for encryption
    pub fn get_encrypt_parameters(&self) -> Option<([u8; KEY_SIZE], [u8; NONCE_SIZE])> {
        self.encrypt.encrypt_parameters
    }
}

// ---------- Writer ----------

pub struct EncryptionLayerWriter<'a, W: 'a + Write> {
    inner: Box<dyn 'a + LayerWriter<'a, W>>,
    cipher: AesGcm256,
    /// Symmetric encryption Key
    key: [u8; KEY_SIZE],
    /// Symmetric encryption nonce prefix, see `build_nonce`
    nonce_prefix: [u8; NONCE_SIZE],
    current_chunk_offset: u64,
    current_ctr: u32,
}

impl<'a, W: 'a + Write> EncryptionLayerWriter<'a, W> {
    pub fn new(
        inner: Box<dyn 'a + LayerWriter<'a, W>>,
        config: &EncryptionConfig,
    ) -> Result<Self, Error> {
        Ok(Self {
            inner,
            key: config.key,
            nonce_prefix: config.nonce,
            cipher: AesGcm256::new(&config.key, &build_nonce(config.nonce, 0), b"")?,
            current_chunk_offset: 0,
            current_ctr: 0,
        })
    }

    fn renew_cipher(&mut self) -> Result<Tag, Error> {
        // Prepare a new cipher
        self.current_ctr += 1;
        self.current_chunk_offset = 0;
        let cipher = AesGcm256::new(
            &self.key,
            &build_nonce(self.nonce_prefix, self.current_ctr),
            b"",
        )?;
        let old_cipher = std::mem::replace(&mut self.cipher, cipher);
        Ok(old_cipher.into_tag())
    }
}

impl<'a, W: 'a + Write> LayerWriter<'a, W> for EncryptionLayerWriter<'a, W> {
    fn into_inner(self) -> Option<Box<dyn 'a + LayerWriter<'a, W>>> {
        Some(self.inner)
    }

    fn into_raw(self: Box<Self>) -> W {
        self.inner.into_raw()
    }

    fn finalize(&mut self) -> Result<(), Error> {
        // Write the tag of the current chunk
        let tag = self.renew_cipher()?;
        self.inner.write_all(&tag)?;

        // Recursive call
        self.inner.finalize()
    }
}

impl<'a, W: Write> Write for EncryptionLayerWriter<'a, W> {
    #[allow(clippy::comparison_chain)]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if self.current_chunk_offset > CHUNK_SIZE {
            // Should never happen
            return Err(
                Error::WrongWriterState("[EncryptWriter] Chunk too big".to_string()).into(),
            );
        } else if self.current_chunk_offset == CHUNK_SIZE {
            // Prepare a new cipher
            let tag = self.renew_cipher()?;
            // Write the previous chunk tag
            self.inner.write_all(&tag)?;
        }

        // StreamingCipher is working in place, so we use a temporary buffer
        let size = std::cmp::min(
            std::cmp::min(CIPHER_BUF_SIZE, buf.len() as u64),
            CHUNK_SIZE - self.current_chunk_offset,
        );
        let mut buf_tmp = Vec::with_capacity(size as usize);
        let buf_src = BufReader::new(buf);
        io::copy(&mut buf_src.take(size), &mut buf_tmp)?;
        self.cipher.encrypt(&mut buf_tmp);
        self.inner.write_all(&buf_tmp)?;
        self.current_chunk_offset += size;
        Ok(size as usize)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

// ---------- Reader ----------

// In the case of stream cipher, encrypting is the same that decrypting. Here, we
// keep the struct separated for any possible future difference
pub struct EncryptionLayerReader<'a, R: Read + Seek> {
    inner: Box<dyn 'a + LayerReader<'a, R>>,
    cipher: AesGcm256,
    key: [u8; KEY_SIZE],
    nonce: [u8; NONCE_SIZE],
    chunk_cache: Cursor<Vec<u8>>,
    current_chunk_number: u32,
}

impl<'a, R: 'a + Read + Seek> EncryptionLayerReader<'a, R> {
    pub fn new(
        inner: Box<dyn 'a + LayerReader<'a, R>>,
        config: &EncryptionReaderConfig,
    ) -> Result<Self, Error> {
        match config.encrypt_parameters {
            Some((key, nonce)) => Ok(Self {
                inner,
                cipher: AesGcm256::new(&key, &build_nonce(nonce, 0), b"")?,
                key,
                nonce,
                chunk_cache: Cursor::new(Vec::with_capacity(CHUNK_SIZE as usize)),
                current_chunk_number: 0,
            }),
            None => Err(Error::PrivateKeyNeeded),
        }
    }

    /// Load the `self.current_chunk_number` chunk in cache
    /// Assume the inner layer is in the correct position
    fn load_in_cache(&mut self) -> Result<Option<()>, Error> {
        self.cipher = AesGcm256::new(
            &self.key,
            &build_nonce(self.nonce, self.current_chunk_number),
            b"",
        )?;

        // Clear current, now useless, allocated memory
        self.chunk_cache.get_mut().clear();

        // Load the current encrypted chunk and the corresponding tag in memory
        let mut data_and_tag = Vec::with_capacity(CHUNK_SIZE as usize + TAG_LENGTH);
        let data_and_tag_read = (&mut self.inner)
            .take(CHUNK_SIZE + TAG_LENGTH as u64)
            .read_to_end(&mut data_and_tag)?;
        // If the inner is at the end of the stream, we cannot read any
        // additional byte -> we must stop
        if data_and_tag_read == 0 {
            return Ok(None);
        }

        // If it is the last block, we may have read less than `CHUNK_SIZE +
        // TAG_LENGTH` bytes. But the `TAG_LENGTH` last bytes are always the tag
        // bytes -> extract it
        let mut tag = [0u8; TAG_LENGTH];
        tag.copy_from_slice(&data_and_tag[data_and_tag_read - TAG_LENGTH..]);
        data_and_tag.resize(data_and_tag_read - TAG_LENGTH, 0);
        let mut data = data_and_tag;

        // Decrypt and verify the current chunk
        let expected_tag = self.cipher.decrypt(data.as_mut_slice());
        if expected_tag.ct_eq(&tag).unwrap_u8() != 1 {
            Err(Error::AuthenticatedDecryptionWrongTag)
        } else {
            self.chunk_cache = Cursor::new(data);
            Ok(Some(()))
        }
    }
}

impl<'a, R: 'a + Read + Seek> LayerReader<'a, R> for EncryptionLayerReader<'a, R> {
    fn into_inner(self) -> Option<Box<dyn 'a + LayerReader<'a, R>>> {
        Some(self.inner)
    }

    fn into_raw(self: Box<Self>) -> R {
        self.inner.into_raw()
    }

    fn initialize(&mut self) -> Result<(), Error> {
        // Recursive call
        self.inner.initialize()?;

        // Load the current buffer in cache
        self.seek(SeekFrom::Start(0))?;
        Ok(())
    }
}

impl<'a, R: 'a + Read + Seek> Read for EncryptionLayerReader<'a, R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let cache_to_consume = CHUNK_SIZE - self.chunk_cache.position();
        if cache_to_consume == 0 {
            // Cache totally consumed, renew it
            self.current_chunk_number += 1;
            if self.load_in_cache()?.is_none() {
                // No more byte in the inner layer
                return Ok(0);
            }
            return self.read(buf);
        }
        // Consume at most the bytes leaving in the cache, to detect the renewal need
        let size = std::cmp::min(cache_to_consume as usize, buf.len());
        self.chunk_cache.read(&mut buf[..size])
    }
}

// Returns how many chunk are present at position `position`
const CHUNK_TAG_SIZE: u64 = CHUNK_SIZE + TAG_LENGTH as u64;

fn no_tag_position_to_tag_position(position: u64) -> u64 {
    let cur_chunk = position / CHUNK_SIZE;
    let cur_chunk_pos = position % CHUNK_SIZE;
    cur_chunk * CHUNK_TAG_SIZE + cur_chunk_pos
}

fn tag_position_to_no_tag_position(position: u64) -> u64 {
    // Assume the position is not inside a tag. If so, round to the end of the
    // current chunk
    let cur_chunk = position / CHUNK_TAG_SIZE;
    let cur_chunk_pos = position % CHUNK_TAG_SIZE;
    cur_chunk * CHUNK_SIZE + std::cmp::min(cur_chunk_pos, CHUNK_SIZE)
}

impl<'a, R: 'a + Read + Seek> Seek for EncryptionLayerReader<'a, R> {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        // `pos` is the position without considering tags
        match pos {
            SeekFrom::Start(pos) => {
                let tag_position = no_tag_position_to_tag_position(pos);
                let chunk_number = tag_position / CHUNK_TAG_SIZE;
                let pos_chunk_start = chunk_number * CHUNK_TAG_SIZE;
                let pos_in_chunk = tag_position % CHUNK_TAG_SIZE;

                // Seek the inner layer at the beginning of the chunk
                self.inner.seek(SeekFrom::Start(pos_chunk_start))?;

                // Load and move into the cache
                self.current_chunk_number = chunk_number as u32;
                self.load_in_cache()?;
                self.chunk_cache.seek(SeekFrom::Start(pos_in_chunk))?;
                Ok(pos)
            }
            SeekFrom::Current(value) => {
                // Inner layer is at the start of the next chunk. The last chunk
                // may not be CHUNK_SIZE long.
                let current_inner = tag_position_to_no_tag_position(self.inner.seek(pos)?);
                let current_inner_chunk = {
                    let chunk_nb = current_inner / CHUNK_SIZE;
                    if chunk_nb == 0 {
                        // Only one chunk, witch is not CHUNK_SIZE long
                        0
                    } else {
                        chunk_nb - 1
                    }
                };
                let current = current_inner_chunk * CHUNK_SIZE + self.chunk_cache.position();
                if value == 0 {
                    // Optimization
                    Ok(current)
                } else {
                    self.seek(SeekFrom::Start((current as i64 + value) as u64))
                }
            }
            SeekFrom::End(pos) => {
                if pos > 0 {
                    // Seeking past the end is unsupported
                    return Err(Error::EndOfStream.into());
                }

                // The last chunk always have a TAG at its end, and might not be
                // CHUNK_SIZE long -> we need to remove the TAG size while
                // converting from tag-aware position to tag-unaware position
                let end_inner_pos = self.inner.seek(SeekFrom::End(0))?;
                let cur_chunk = end_inner_pos / CHUNK_TAG_SIZE;
                let cur_chunk_pos = end_inner_pos % CHUNK_TAG_SIZE;
                let end_pos = cur_chunk * CHUNK_SIZE + cur_chunk_pos - TAG_LENGTH as u64;
                self.seek(SeekFrom::Start((pos + end_pos as i64) as u64))
            }
        }
    }
}

// ---------- Fail-Safe Reader ----------

pub struct EncryptionLayerFailSafeReader<'a, R: Read> {
    inner: Box<dyn 'a + LayerFailSafeReader<'a, R>>,
    cipher: AesGcm256,
    key: [u8; KEY_SIZE],
    nonce: [u8; NONCE_SIZE],
    current_chunk_number: u32,
    current_chunk_offset: u64,
}

impl<'a, R: 'a + Read> EncryptionLayerFailSafeReader<'a, R> {
    pub fn new(
        inner: Box<dyn 'a + LayerFailSafeReader<'a, R>>,
        config: &EncryptionReaderConfig,
    ) -> Result<Self, Error> {
        match config.encrypt_parameters {
            Some((key, nonce)) => Ok(Self {
                inner,
                cipher: AesGcm256::new(&key, &build_nonce(nonce, 0), b"")?,
                key,
                nonce,
                current_chunk_number: 0,
                current_chunk_offset: 0,
            }),
            None => Err(Error::PrivateKeyNeeded),
        }
    }
}

impl<'a, R: 'a + Read> LayerFailSafeReader<'a, R> for EncryptionLayerFailSafeReader<'a, R> {
    fn into_inner(self) -> Option<Box<dyn 'a + LayerFailSafeReader<'a, R>>> {
        Some(self.inner)
    }

    fn into_raw(self: Box<Self>) -> R {
        self.inner.into_raw()
    }
}

impl<'a, R: Read> Read for EncryptionLayerFailSafeReader<'a, R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.current_chunk_offset == CHUNK_SIZE {
            // Ignore the tag and renew the cipher
            io::copy(
                &mut (&mut self.inner).take(TAG_LENGTH as u64),
                &mut io::sink(),
            )?;
            self.current_chunk_number += 1;
            self.current_chunk_offset = 0;
            self.cipher = AesGcm256::new(
                &self.key,
                &build_nonce(self.nonce, self.current_chunk_number),
                b"",
            )?;
            return self.read(buf);
        }

        // AesGcm256 is working in place, so we use a temporary buffer
        let mut buf_tmp = [0u8; CIPHER_BUF_SIZE as usize];
        let size = std::cmp::min(CIPHER_BUF_SIZE as usize, buf.len());
        // Read at most the chunk size, to detect when renewal is needed
        let size = std::cmp::min((CHUNK_SIZE - self.current_chunk_offset) as usize, size);
        let len = self.inner.read(&mut buf_tmp[..size])?;
        self.current_chunk_offset += len as u64;
        self.cipher.decrypt_unauthenticated(&mut buf_tmp[..len]);
        (&buf_tmp[..len]).read_exact(&mut buf[..len])?;
        Ok(len)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use rand::distributions::{Alphanumeric, Distribution};
    use rand::rngs::StdRng;
    use rand::SeedableRng;
    use std::io::{Cursor, Read, Seek, SeekFrom, Write};

    use crate::layers::raw::{RawLayerFailSafeReader, RawLayerReader, RawLayerWriter};

    static FAKE_FILE: [u8; 26] = *b"abcdefghijklmnopqrstuvwxyz";
    static KEY: [u8; KEY_SIZE] = [2u8; KEY_SIZE];
    static NONCE: [u8; NONCE_SIZE] = [3u8; NONCE_SIZE];

    fn encrypt_write(file: Vec<u8>) -> Vec<u8> {
        // Instantiate a EncryptionLayerWriter and fill it with FAKE_FILE
        let mut encrypt_w = Box::new(
            EncryptionLayerWriter::new(
                Box::new(RawLayerWriter::new(file)),
                &EncryptionConfig {
                    ecc_keys: Vec::new(),
                    key: KEY,
                    nonce: NONCE,
                },
            )
            .unwrap(),
        );
        encrypt_w.write_all(&FAKE_FILE[..21]).unwrap();
        encrypt_w.write_all(&FAKE_FILE[21..]).unwrap();
        encrypt_w.finalize().unwrap();

        let out = encrypt_w.into_raw();
        assert_eq!(out.len(), FAKE_FILE.len() + TAG_LENGTH);
        assert_ne!(out[..FAKE_FILE.len()], FAKE_FILE);
        out
    }

    #[test]
    fn encrypt_layer() {
        let file = Vec::new();
        let out = encrypt_write(file);

        let buf = Cursor::new(out.as_slice());
        let config = EncryptionReaderConfig {
            private_keys: Vec::new(),
            encrypt_parameters: Some((KEY, NONCE)),
        };
        let mut encrypt_r =
            EncryptionLayerReader::new(Box::new(RawLayerReader::new(buf)), &config).unwrap();
        encrypt_r.initialize().unwrap();
        let mut output = Vec::new();
        encrypt_r.read_to_end(&mut output).unwrap();
        assert_eq!(output, FAKE_FILE);
    }

    #[test]
    fn encrypt_failsafe_layer() {
        let file = Vec::new();
        let out = encrypt_write(file);

        let config = EncryptionReaderConfig {
            private_keys: Vec::new(),
            encrypt_parameters: Some((KEY, NONCE)),
        };
        let mut encrypt_r = EncryptionLayerFailSafeReader::new(
            Box::new(RawLayerFailSafeReader::new(out.as_slice())),
            &config,
        )
        .unwrap();
        let mut output = Vec::new();
        encrypt_r.read_to_end(&mut output).unwrap();
        // Extra output expected, due to the ignored tag in the last chunk
        assert_eq!(output[..FAKE_FILE.len()], FAKE_FILE);
    }

    #[test]
    fn encrypt_failsafe_truncated() {
        let file = Vec::new();
        let out = encrypt_write(file);

        // Truncate at the middle
        let stop = out.len() / 2;

        let config = EncryptionReaderConfig {
            private_keys: Vec::new(),
            encrypt_parameters: Some((KEY, NONCE)),
        };
        let mut encrypt_r = EncryptionLayerFailSafeReader::new(
            Box::new(RawLayerFailSafeReader::new(&out[..stop])),
            &config,
        )
        .unwrap();
        let mut output = Vec::new();
        encrypt_r.read_to_end(&mut output).unwrap();
        // Thanks to the encrypt layer construction, we can recover `stop` bytes
        assert_eq!(output.as_slice(), &FAKE_FILE[..stop]);
    }

    #[test]
    fn seek_encrypt() {
        // First, encrypt a dummy file
        let file = Vec::new();
        let out = encrypt_write(file);

        // Normal decryption
        let buf = Cursor::new(out.as_slice());
        let config = EncryptionReaderConfig {
            private_keys: Vec::new(),
            encrypt_parameters: Some((KEY, NONCE)),
        };
        let mut encrypt_r =
            EncryptionLayerReader::new(Box::new(RawLayerReader::new(buf)), &config).unwrap();
        encrypt_r.initialize().unwrap();
        let mut output = Vec::new();
        encrypt_r.read_to_end(&mut output).unwrap();
        assert_eq!(output, FAKE_FILE);

        // Seek and decrypt twice the same thing
        let pos = encrypt_r.seek(SeekFrom::Current(0)).unwrap();
        // test the current position retrievial
        assert_eq!(pos, tag_position_to_no_tag_position(FAKE_FILE.len() as u64));
        // decrypt twice the same thing, with an offset
        let pos = encrypt_r.seek(SeekFrom::Start(5)).unwrap();
        assert_eq!(pos, 5);
        let mut output = Vec::new();
        encrypt_r.read_to_end(&mut output).unwrap();
        println!("{:?}", output);
        assert_eq!(output.as_slice(), &FAKE_FILE[5..]);
    }

    #[test]
    fn encrypt_op_chunk_size() {
        // Operate near the chunk size

        // Instantiate a EncryptionLayerWriter and fill it with at least CHUNK_SIZE data
        let file = Vec::new();
        let mut encrypt_w = Box::new(
            EncryptionLayerWriter::new(
                Box::new(RawLayerWriter::new(file)),
                &EncryptionConfig {
                    ecc_keys: Vec::new(),
                    key: KEY,
                    nonce: NONCE,
                },
            )
            .unwrap(),
        );
        let length = (CHUNK_SIZE * 2) as usize;
        let mut rng: StdRng = SeedableRng::from_seed([0u8; 32]);
        let data: Vec<u8> = Alphanumeric
            .sample_iter(&mut rng)
            .take(length)
            .map(|c| c as u8)
            .collect();
        encrypt_w.write_all(&data).unwrap();
        encrypt_w.finalize().unwrap();

        let out = encrypt_w.into_raw();
        assert_eq!(out.len(), length + 2 * TAG_LENGTH);
        assert_ne!(&out[..length], data.as_slice());

        // Normal decryption
        let buf = Cursor::new(out.as_slice());
        let config = EncryptionReaderConfig {
            private_keys: Vec::new(),
            encrypt_parameters: Some((KEY, NONCE)),
        };
        let mut encrypt_r =
            EncryptionLayerReader::new(Box::new(RawLayerReader::new(buf)), &config).unwrap();
        encrypt_r.initialize().unwrap();
        let mut output = Vec::new();
        encrypt_r.read_to_end(&mut output).unwrap();
        assert_eq!(output, data);

        // Seek and decrypt twice the same thing
        let pos = encrypt_r.seek(SeekFrom::Start(CHUNK_SIZE)).unwrap();
        assert_eq!(pos, CHUNK_SIZE);
        let mut output = Vec::new();
        encrypt_r.read_to_end(&mut output).unwrap();
        assert_eq!(output.as_slice(), &data[CHUNK_SIZE as usize..]);
    }
}