cocoon 0.4.3

A simple protected container with strong encryption and format validation.
Documentation
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
use aes_gcm::{
    aead::{generic_array::GenericArray, KeyInit},
    AeadInPlace, Aes256Gcm,
};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use chacha20poly1305::ChaCha20Poly1305;
use rand::{rngs::StdRng, RngCore, SeedableRng};
#[cfg(feature = "std")]
use std::io::{Read, Write};
use zeroize::Zeroizing;

use super::{
    error::Error,
    format::MiniFormatPrefix,
    header::{CocoonCipher, CocoonConfig, CocoonKdf, MiniCocoonHeader},
    kdf::{self, KEY_SIZE},
};

/// The size of the cocoon prefix which appears in detached form in [`MiniCocoon::encrypt`].
pub const MINI_PREFIX_SIZE: usize = MiniFormatPrefix::SERIALIZE_SIZE;

/// This is a mini cocoon for a convenient and cool encryption.
#[derive(Clone)]
pub struct MiniCocoon {
    key: Zeroizing<[u8; KEY_SIZE]>,
    rng: StdRng,
    config: CocoonConfig,
}

/// Stores data securely inside of a simple encrypted container ("mini cocoon").
///
/// # Basic Usage
/// ```
/// # use cocoon::{MiniCocoon, Error};
/// #
/// # fn main() -> Result<(), Error> {
/// let mut cocoon = MiniCocoon::from_key(b"0123456789abcdef0123456789abcdef", &[0; 32]);
///
/// let wrapped = cocoon.wrap(b"my secret data")?;
/// assert_ne!(&wrapped, b"my secret data");
///
/// let unwrapped = cocoon.unwrap(&wrapped)?;
/// assert_eq!(unwrapped, b"my secret data");
///
/// # Ok(())
/// # }
/// ```
///
/// Scroll down to [Features and Methods Mapping](#features-and-methods-mapping), and also see
/// crate's documentation for more use cases.
///
/// # Default Configuration
/// | Option                      | Value                          |
/// |-----------------------------|--------------------------------|
/// | [Cipher](CocoonCipher)      | Chacha20Poly1305               |
/// | [Key derivation](CocoonKdf) | PBKDF2 with 100 000 iterations |
///
/// * Cipher can be customized using [`MiniCocoon::with_cipher`] method.
/// * Key derivation (KDF): only PBKDF2 is supported.
///
/// # Features and Methods Mapping
///
/// _Note: It is maybe not a complete list of API methods. Please, refer to the current
/// documentation below to get familiarized with the full set of methods._
///
/// | Method ↓ / Feature →          | `std` | `alloc` | "no_std" |
/// |-------------------------------|:-----:|:-------:|:--------:|
/// | [`MiniCocoon::from_key`]      | ✔️    | ✔️      | ✔️      |
/// | [`MiniCocoon::from_password`] | ✔️    | ✔️      | ✔️      |
/// | [`MiniCocoon::encrypt`]       | ✔️    | ✔️      | ✔️      |
/// | [`MiniCocoon::decrypt`]       | ✔️    | ✔️      | ✔️      |
/// | [`MiniCocoon::wrap`]          | ✔️    | ✔️      | ❌      |
/// | [`MiniCocoon::unwrap`]        | ✔️    | ✔️      | ❌      |
/// | [`MiniCocoon::dump`]          | ✔️    | ❌      | ❌      |
/// | [`MiniCocoon::parse`]         | ✔️    | ❌      | ❌      |
impl MiniCocoon {
    /// Creates a new [`MiniCocoon`] with a symmetric key seeding a random generator
    /// using a given `seed` buffer.
    ///
    /// * `key` - a symmetric key of length 32
    /// * `seed` - 32 random bytes to initialize an internal random generator
    ///
    /// # Examples
    /// ```
    /// use cocoon::MiniCocoon;
    /// use rand::Rng;
    ///
    /// // Seed can be obtained by any cryptographically secure random generator.
    /// // ThreadRng is used as an example.
    /// let seed = rand::thread_rng().gen::<[u8; 32]>();
    ///
    /// // Key must be 32 bytes of length. Let it be another 32 random bytes.
    /// let key = rand::thread_rng().gen::<[u8; 32]>();
    ///
    /// let mut cocoon = MiniCocoon::from_key(&key, &seed);
    /// ```
    pub fn from_key(key: &[u8], seed: &[u8]) -> Self {
        let mut k = [0u8; KEY_SIZE];
        let mut s = [0u8; KEY_SIZE];

        k.copy_from_slice(key);
        s.copy_from_slice(seed);

        let key = Zeroizing::new(k);
        let rng = StdRng::from_seed(s);

        MiniCocoon {
            key,
            rng,
            config: CocoonConfig::default(),
        }
    }

    /// Creates a new [`MiniCocoon`] with a password. Under the hood, an encryption key is created
    /// from the password using PBKDF2 algorithm.
    ///
    /// * `password` - a password of any length
    /// * `seed` - 32 random bytes to initialize an internal random generator
    ///
    /// # Examples
    /// ```
    /// use cocoon::MiniCocoon;
    /// use rand::Rng;
    ///
    /// // Seed can be obtained by any cryptographically secure random generator.
    /// // ThreadRng is used as an example.
    /// let seed = rand::thread_rng().gen::<[u8; 32]>();
    ///
    /// let mut cocoon = MiniCocoon::from_password(b"my password", &seed);
    /// ```
    pub fn from_password(password: &[u8], seed: &[u8]) -> Self {
        let config = CocoonConfig::default();
        let key = match config.kdf() {
            CocoonKdf::Pbkdf2 => kdf::pbkdf2::derive(seed, password, config.kdf_iterations()),
        };

        let mut s = [0u8; KEY_SIZE];
        s.copy_from_slice(seed);

        let rng = StdRng::from_seed(s);

        MiniCocoon { key, rng, config }
    }

    /// Sets an encryption algorithm to wrap data on.
    ///
    /// # Examples
    /// ```
    /// use cocoon::{MiniCocoon, CocoonCipher};
    /// use rand::Rng;
    ///
    /// let seed = rand::thread_rng().gen::<[u8; 32]>();
    /// let key = rand::thread_rng().gen::<[u8; 32]>();
    ///
    /// let mut cocoon = MiniCocoon::from_key(&key, &seed).with_cipher(CocoonCipher::Chacha20Poly1305);
    /// cocoon.wrap(b"my secret data");
    /// ```
    pub fn with_cipher(mut self, cipher: CocoonCipher) -> Self {
        self.config = self.config.with_cipher(cipher);
        self
    }

    /// Wraps data to an encrypted container.
    ///
    /// * `data` - a sensitive user data
    ///
    /// Examples:
    /// ```
    /// # use cocoon::{MiniCocoon, Error};
    /// # use rand::Rng;
    /// #
    /// # fn main() -> Result<(), Error> {
    /// let seed = rand::thread_rng().gen::<[u8; 32]>();
    /// let mut cocoon = MiniCocoon::from_password(b"password", &seed);
    ///
    /// let wrapped = cocoon.wrap(b"my secret data")?;
    /// assert_ne!(&wrapped, b"my secret data");
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "alloc")]
    #[cfg_attr(docs_rs, doc(cfg(any(feature = "alloc", feature = "std"))))]
    pub fn wrap(&mut self, data: &[u8]) -> Result<Vec<u8>, Error> {
        // Allocation is needed because there is no way to prefix encrypted
        // data with a header without an allocation. It means that we need
        // to copy data at least once. It's necessary to avoid any further copying.
        let mut container = Vec::with_capacity(MINI_PREFIX_SIZE + data.len());
        container.extend_from_slice(&[0; MINI_PREFIX_SIZE]);
        container.extend_from_slice(data);

        let body = &mut container[MINI_PREFIX_SIZE..];

        // Encrypt in place and get a prefix part.
        let detached_prefix = self.encrypt(body)?;

        container[..MINI_PREFIX_SIZE].copy_from_slice(&detached_prefix);

        Ok(container)
    }

    /// Encrypts data in place, taking ownership over the buffer, and dumps the container
    /// into [`File`](std::fs::File), [`Cursor`](std::io::Cursor), or any other writer.
    /// * `data` - a sensitive data inside of [`Vec`] to be encrypted in place
    /// * `writer` - [`File`](std::fs::File), [`Cursor`](`std::io::Cursor`), or any other output
    ///
    /// A data is going to be encrypted in place and stored in a file using the "mini cocoon"
    /// [format](#format).
    ///
    /// # Examples
    /// ```
    /// # use cocoon::{MiniCocoon, Error};
    /// # use rand::Rng;
    /// # use std::io::Cursor;
    /// #
    /// # fn main() -> Result<(), Error> {
    /// let key = [ 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];
    /// let seed = rand::thread_rng().gen::<[u8; 32]>();
    ///
    /// let mut cocoon = MiniCocoon::from_key(&key, &seed);
    /// # let mut file = Cursor::new(vec![0; 150]);
    ///
    /// let mut data = b"my secret data".to_vec();
    ///
    /// cocoon.dump(data, &mut file)?;
    /// # assert_ne!(file.get_ref(), b"my secret data");
    ///
    /// # Ok(())
    /// # }
    #[cfg(feature = "std")]
    #[cfg_attr(docs_rs, doc(cfg(feature = "std")))]
    pub fn dump(&mut self, mut data: Vec<u8>, writer: &mut impl Write) -> Result<(), Error> {
        let detached_prefix = self.encrypt(&mut data)?;

        writer.write_all(&detached_prefix)?;
        writer.write_all(&data)?;

        Ok(())
    }

    /// Encrypts data in place and returns a detached prefix of the container.
    ///
    /// The prefix is needed to decrypt data with [`MiniCocoon::decrypt`].
    /// This method doesn't use memory allocation and it is suitable in the build
    /// with no [`std`] and no [`alloc`].
    ///
    /// <img alt="Detached prefix" src="https://github.com/fadeevab/cocoon/raw/main/images/cocoon_detached_prefix.svg" />
    ///
    /// # Examples
    /// ```
    /// # use cocoon::{MiniCocoon, Error};
    /// #
    /// # fn main() -> Result<(), Error> {
    /// let mut cocoon = MiniCocoon::from_password(b"password", &[1; 32]);
    ///
    /// let mut data = "my secret data".to_owned().into_bytes();
    ///
    /// let detached_prefix = cocoon.encrypt(&mut data)?;
    /// assert_ne!(data, b"my secret data");
    /// # Ok(())
    /// # }
    /// ```
    pub fn encrypt(&mut self, data: &mut [u8]) -> Result<[u8; MINI_PREFIX_SIZE], Error> {
        let mut nonce = [0u8; 12];
        self.rng.fill_bytes(&mut nonce);

        let header = MiniCocoonHeader::new(nonce, data.len());
        let prefix = MiniFormatPrefix::new(header);

        let nonce = GenericArray::from_slice(&nonce);
        let key = GenericArray::clone_from_slice(self.key.as_ref());

        let tag: [u8; 16] = match self.config.cipher() {
            CocoonCipher::Chacha20Poly1305 => {
                let cipher = ChaCha20Poly1305::new(&key);
                cipher.encrypt_in_place_detached(nonce, prefix.prefix(), data)
            }
            CocoonCipher::Aes256Gcm => {
                let cipher = Aes256Gcm::new(&key);
                cipher.encrypt_in_place_detached(nonce, prefix.prefix(), data)
            }
        }
        .map_err(|_| Error::Cryptography)?
        .into();

        Ok(prefix.serialize(&tag))
    }

    /// Unwraps data from the encrypted container (see [`MiniCocoon::wrap`]).
    ///
    /// # Examples
    /// ```
    /// # use cocoon::{MiniCocoon, Error};
    /// # use rand::Rng;
    /// #
    /// # fn main() -> Result<(), Error> {
    /// let key = b"0123456789abcdef0123456789abcdef";
    /// let seed = rand::thread_rng().gen::<[u8; 32]>();
    ///
    /// let mut cocoon = MiniCocoon::from_key(key, &seed);
    ///
    /// # let wrapped = cocoon.wrap(b"my secret data")?;
    /// # assert_ne!(&wrapped, b"my secret data");
    /// #
    /// let unwrapped = cocoon.unwrap(&wrapped)?;
    /// assert_eq!(unwrapped, b"my secret data");
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "alloc")]
    #[cfg_attr(docs_rs, doc(cfg(any(feature = "alloc", feature = "std"))))]
    pub fn unwrap(&self, container: &[u8]) -> Result<Vec<u8>, Error> {
        let prefix = MiniFormatPrefix::deserialize(container)?;
        let header = prefix.header();

        if container.len() < MINI_PREFIX_SIZE + header.data_length() {
            return Err(Error::TooShort);
        }

        let mut body = Vec::with_capacity(header.data_length());
        body.extend_from_slice(&container[MINI_PREFIX_SIZE..MINI_PREFIX_SIZE + body.capacity()]);

        self.decrypt_parsed(&mut body, &prefix)?;

        Ok(body)
    }

    /// Parses container from the reader (file, cursor, etc.), validates format,
    /// allocates memory and places decrypted data there.
    ///
    /// * `reader` - [`File`](std::fs::File), [`Cursor`](`std::io::Cursor`), or any other input
    ///
    /// # Examples
    /// ```
    /// # use cocoon::{MiniCocoon, Error};
    /// # use rand::Rng;
    /// # use std::io::Cursor;
    /// #
    /// # fn main() -> Result<(), Error> {
    /// let key = b"0123456789abcdef0123456789abcdef";
    /// let seed = rand::thread_rng().gen::<[u8; 32]>();
    ///
    /// let mut cocoon = MiniCocoon::from_key(key, &seed);
    /// # let mut file = Cursor::new(vec![0; 150]);
    /// #
    /// # let mut data = b"my secret data".to_vec();
    /// #
    /// # cocoon.dump(data, &mut file)?;
    /// # assert_ne!(file.get_ref(), b"my secret data");
    /// #
    /// # file.set_position(0);
    ///
    /// let data = cocoon.parse(&mut file)?;
    /// assert_eq!(&data, b"my secret data");
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "std")]
    #[cfg_attr(docs_rs, doc(cfg(feature = "std")))]
    pub fn parse(&self, reader: &mut impl Read) -> Result<Vec<u8>, Error> {
        let prefix = MiniFormatPrefix::deserialize_from(reader)?;
        let mut body = vec![0; prefix.header().data_length()];

        // Too short error can be thrown right from here.
        reader.read_exact(&mut body)?;

        self.decrypt_parsed(&mut body, &prefix)?;

        Ok(body)
    }

    /// Decrypts data in place using the parts returned by [`MiniCocoon::encrypt`] method.
    ///
    /// The method doesn't use memory allocation and is suitable for "no std" and "no alloc" build.
    ///
    /// # Examples
    /// ```
    /// # use cocoon::{MiniCocoon, Error};
    /// #
    /// # fn main() -> Result<(), Error> {
    /// let mut data = "my secret data".to_owned().into_bytes();
    /// let mut cocoon = MiniCocoon::from_password(b"password", &[0; 32]);
    ///
    /// let detached_prefix = cocoon.encrypt(&mut data)?;
    /// assert_ne!(data, b"my secret data");
    ///
    /// cocoon.decrypt(&mut data, &detached_prefix)?;
    /// assert_eq!(data, b"my secret data");
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn decrypt(&self, data: &mut [u8], detached_prefix: &[u8]) -> Result<(), Error> {
        let prefix = MiniFormatPrefix::deserialize(detached_prefix)?;

        self.decrypt_parsed(data, &prefix)
    }

    fn decrypt_parsed(
        &self,
        data: &mut [u8],
        detached_prefix: &MiniFormatPrefix,
    ) -> Result<(), Error> {
        let mut nonce = [0u8; 12];

        let header = detached_prefix.header();

        if data.len() < header.data_length() {
            return Err(Error::TooShort);
        }

        let data = &mut data[..header.data_length()];

        nonce.copy_from_slice(header.nonce());

        let nonce = GenericArray::from_slice(&nonce);
        let master_key = GenericArray::clone_from_slice(self.key.as_ref());
        let tag = GenericArray::from_slice(detached_prefix.tag());

        match self.config.cipher() {
            CocoonCipher::Chacha20Poly1305 => {
                let cipher = ChaCha20Poly1305::new(&master_key);
                cipher.decrypt_in_place_detached(nonce, detached_prefix.prefix(), data, tag)
            }
            CocoonCipher::Aes256Gcm => {
                let cipher = Aes256Gcm::new(&master_key);
                cipher.decrypt_in_place_detached(nonce, detached_prefix.prefix(), data, tag)
            }
        }
        .map_err(|_| Error::Cryptography)?;

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use std::fs::File;
    use std::io::Cursor;

    use super::*;

    #[test]
    fn mini_cocoon_create() {
        MiniCocoon::from_password(b"password", &[0; 32]);
        MiniCocoon::from_key(&[1; 32], &[0; 32]);
    }

    #[test]
    fn mini_cocoon_clone() {
        let mut cocoon = MiniCocoon::from_password(b"password", &[0; 32]);
        let cloned_cocoon = cocoon.clone();
        const DATA: &'static [u8] = b"my-sercet-data";

        // To check whether MiniCocoon gets cloned properly
        let wrapped = cocoon.wrap(DATA).unwrap();
        drop(cocoon);

        let unwrapped = cloned_cocoon.unwrap(&wrapped).unwrap();
        assert_eq!(&unwrapped, DATA);
    }

    #[test]
    fn mini_cocoon_encrypt() {
        let mut cocoon = MiniCocoon::from_password(b"password", &[0; 32]);
        let mut data = "my secret data".to_owned().into_bytes();

        let detached_prefix = cocoon.encrypt(&mut data).unwrap();

        assert_eq!(
            &[
                155, 244, 154, 106, 7, 85, 249, 83, 129, 31, 206, 18, 0, 0, 0, 0, 0, 0, 0, 14, 88,
                114, 102, 98, 71, 228, 153, 231, 144, 157, 177, 113, 160, 209, 154, 83
            ][..],
            &detached_prefix[..]
        );

        assert_eq!(
            &[98, 34, 35, 62, 28, 121, 71, 223, 170, 151, 215, 104, 52, 187],
            &data[..]
        );

        let mut cipher_data: Vec<Vec<u8>> = Vec::new();
        cipher_data.push(data.to_vec());
        for _ in 0..10 {
            data = "my secret data".to_owned().into_bytes();
            let _ = cocoon.encrypt(&mut data).unwrap();
            cipher_data.push(data.to_vec());
            for i in 0..cipher_data.len() - 2 {
                assert_ne!(&cipher_data.last().unwrap(), &cipher_data.get(i).unwrap())
            }
        }
    }

    #[test]
    fn mini_cocoon_encrypt_aes() {
        let mut cocoon =
            MiniCocoon::from_password(b"password", &[0; 32]).with_cipher(CocoonCipher::Aes256Gcm);
        let mut data = "my secret data".to_owned().into_bytes();

        let detached_prefix = cocoon.encrypt(&mut data).unwrap();

        assert_eq!(
            &[
                155, 244, 154, 106, 7, 85, 249, 83, 129, 31, 206, 18, 0, 0, 0, 0, 0, 0, 0, 14, 95,
                1, 247, 191, 121, 127, 53, 49, 59, 241, 134, 122, 122, 207, 110, 138
            ][..],
            &detached_prefix[..]
        );

        assert_eq!(
            &[41, 58, 226, 219, 28, 132, 21, 216, 165, 46, 246, 120, 10, 92],
            &data[..]
        );

        let mut cipher_data: Vec<Vec<u8>> = Vec::new();
        cipher_data.push(data.to_vec());
        for _ in 0..10 {
            data = "my secret data".to_owned().into_bytes();
            let _ = cocoon.encrypt(&mut data).unwrap();
            cipher_data.push(data.to_vec());
            for i in 0..cipher_data.len() - 2 {
                assert_ne!(&cipher_data.last().unwrap(), &cipher_data.get(i).unwrap())
            }
        }
    }

    #[test]
    fn mini_cocoon_decrypt() {
        let detached_prefix = [
            118, 184, 224, 173, 160, 241, 61, 144, 64, 93, 106, 229, 0, 0, 0, 0, 0, 0, 0, 14, 159,
            31, 100, 63, 43, 219, 99, 46, 201, 213, 205, 233, 174, 235, 43, 24,
        ];
        let mut data = [
            224, 50, 239, 254, 30, 140, 44, 135, 217, 94, 127, 67, 78, 31,
        ];
        let cocoon = MiniCocoon::from_password(b"password", &[0; 32]);

        cocoon
            .decrypt(&mut data, &detached_prefix)
            .expect("Decrypted data");

        assert_eq!(b"my secret data", &data);
    }

    #[test]
    fn mini_cocoon_decrypt_aes() {
        let detached_prefix = [
            118, 184, 224, 173, 160, 241, 61, 144, 64, 93, 106, 229, 0, 0, 0, 0, 0, 0, 0, 14, 165,
            83, 248, 230, 121, 148, 146, 253, 98, 153, 208, 174, 129, 31, 162, 13,
        ];
        let mut data = [
            178, 119, 26, 64, 67, 5, 235, 21, 238, 150, 245, 172, 197, 114,
        ];
        let cocoon =
            MiniCocoon::from_password(b"password", &[0; 32]).with_cipher(CocoonCipher::Aes256Gcm);

        cocoon
            .decrypt(&mut data, &detached_prefix)
            .expect("Decrypted data");

        assert_eq!(b"my secret data", &data);
    }

    #[test]
    fn mini_cocoon_wrap() {
        let mut cocoon = MiniCocoon::from_password(b"password", &[0; 32]);
        let wrapped = cocoon.wrap(b"data").expect("Wrapped container");

        assert_eq!(wrapped[wrapped.len() - 4..], [107, 58, 119, 44]);
    }

    #[test]
    fn mini_cocoon_wrap_unwrap() {
        let mut cocoon = MiniCocoon::from_key(&[1; 32], &[0; 32]);
        let wrapped = cocoon.wrap(b"data").expect("Wrapped container");
        let original = cocoon.unwrap(&wrapped).expect("Unwrapped container");

        assert_eq!(original, b"data");
    }

    #[test]
    fn mini_cocoon_wrap_unwrap_corrupted() {
        let mut cocoon = MiniCocoon::from_key(&[1; 32], &[0; 32]);
        let mut wrapped = cocoon.wrap(b"data").expect("Wrapped container");

        let last = wrapped.len() - 1;
        wrapped[last] += 1;
        let _ = &cocoon.unwrap(&wrapped).expect_err("Unwrapped container");
    }

    #[test]
    fn mini_cocoon_unwrap_larger_is_ok() {
        let mut cocoon = MiniCocoon::from_key(&[1; 32], &[0; 32]);
        let mut wrapped = cocoon.wrap(b"data").expect("Wrapped container");

        wrapped.push(0);
        let original = cocoon.unwrap(&wrapped).expect("Unwrapped container");

        assert_eq!(original, b"data");
    }

    #[test]
    fn mini_cocoon_unwrap_too_short() {
        let mut cocoon = MiniCocoon::from_key(&[1; 32], &[0; 32]);
        let mut wrapped = cocoon.wrap(b"data").expect("Wrapped container");

        wrapped.pop();
        cocoon.unwrap(&wrapped).expect_err("Too short");
    }

    #[test]
    fn cocoon_decrypt_wrong_sizes() {
        let detached_prefix = [
            118, 184, 224, 173, 160, 241, 61, 144, 64, 93, 106, 229, 0, 0, 0, 0, 0, 0, 0, 14, 165,
            83, 248, 230, 121, 148, 146, 253, 98, 153, 208, 174, 129, 31, 162, 13,
        ];
        let mut data = [
            178, 119, 26, 64, 67, 5, 235, 21, 238, 150, 245, 172, 197, 114, 0,
        ];
        let cocoon =
            MiniCocoon::from_password(b"password", &[0; 32]).with_cipher(CocoonCipher::Aes256Gcm);

        cocoon
            .decrypt(&mut data, &detached_prefix)
            .expect("Decrypted data");

        assert_eq!(b"my secret data\0", &data);

        cocoon
            .decrypt(&mut data[..4], &detached_prefix)
            .expect_err("Too short");
    }

    #[test]
    fn mini_cocoon_dump_parse() {
        let buf = vec![0; 100];
        let mut file = Cursor::new(buf);
        let mut cocoon = MiniCocoon::from_key(&[1; 32], &[0; 32]);

        // Prepare data inside of `Vec` container.
        let data = b"my data".to_vec();

        cocoon.dump(data, &mut file).expect("Dumped container");
        assert_ne!(b"my data", file.get_ref().as_slice());

        // "Re-open" the file.
        file.set_position(0);

        let original = cocoon.parse(&mut file).expect("Parsed container");
        assert_eq!(b"my data", original.as_slice());
    }

    #[test]
    fn mini_cocoon_dump_io_error() {
        let read_only_file =
            std::env::var("CARGO_TARGET_DIR").unwrap_or("target".into()) + "/read_only.txt";

        File::create(read_only_file.clone()).expect("Test file");
        let mut file = File::open(read_only_file).expect("Test file");

        let mut cocoon = MiniCocoon::from_key(&[1; 32], &[0; 32]);

        // Prepare data inside of `Vec` container.
        let data = b"my data".to_vec();

        match cocoon.dump(data, &mut file) {
            Err(e) => match e {
                Error::Io(_) => (),
                _ => panic!("Only unexpected I/O error is expected :)"),
            },
            _ => panic!("Success is not expected"),
        }
    }

    #[test]
    fn mini_cocoon_parse_io_error() {
        let read_only_file =
            std::env::var("CARGO_TARGET_DIR").unwrap_or("target".into()) + "/read_only.txt";

        File::create(read_only_file.clone()).expect("Test file");
        let mut file = File::open(read_only_file).expect("Test file");

        let cocoon = MiniCocoon::from_key(&[1; 32], &[0; 32]);

        match cocoon.parse(&mut file) {
            Err(e) => match e {
                Error::TooShort => (),
                _ => panic!("TooShort is expected for an empty file"),
            },
            _ => panic!("Success is not expected"),
        }
    }
}