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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
/*!
CoDeCs Module

Performs Basic AES256-CBC Encryption and Decryption without HMAC: the
IV application in the first plaintext block is up to the user for
now...

# Example


```
use obg::aescbc::cdc::Aes256CbcCodec;
```
*/

pub use crate::aescbc::kd::pbkdf2_sha384_128bits;
pub use crate::aescbc::kd::pbkdf2_sha384_256bits;
pub use crate::aescbc::kd::pbkdf2_sha512;
pub use crate::aescbc::kd::DerivationScheme;
pub use crate::aescbc::pad::Ansix923;
pub use crate::aescbc::pad::Padder128;
pub use crate::aescbc::pad::Padding;
pub use crate::aescbc::tp::{B128, B256};
pub use crate::errors::Error;
pub use crate::hashis::gcrc128;
pub use crate::hashis::gcrc256;
pub use crate::ioutils::{absolute_path, open_write, read_bytes, read_bytes_high_water_mark};
use hex;
use rand::prelude::*;

use aes::cipher::{
    // generic_array::{GenericArray, ArrayLength, typenum::U8};
    generic_array::GenericArray,
    BlockDecrypt,
    BlockEncrypt,
    KeyInit,
};
use aes::Aes256;
use chrono::{DateTime, Utc};
use std::io::Write;
use std::path::Path;

pub trait EncryptionEngine {
    fn encrypt_block(&self, plaintext: &[u8], xor_block: &[u8]) -> Vec<u8>;
    fn decrypt_block(&self, ciphertext: &[u8], xor_block: &[u8]) -> Vec<u8>;
    fn encrypt_blocks(&self, plaintext: &[u8]) -> Vec<u8>;
    fn decrypt_blocks(&self, ciphertext: &[u8]) -> Vec<u8>;
}

pub fn xor_128(left: B128, right: B128) -> B128 {
    let mut result: B128 = [0; 16];
    for (i, (s, o)) in left.into_iter().zip(right.iter()).enumerate() {
        result[i] = s ^ o;
    }
    result
}

pub fn xor_256(left: B256, right: B256) -> B256 {
    let mut result: B256 = [0; 32];
    for (i, (s, o)) in left.into_iter().zip(right.iter()).enumerate() {
        result[i] = s ^ o;
    }
    result
}

pub fn xor(a: &[u8], b: &[u8]) -> Vec<u8> {
    a.into_iter().zip(b.iter()).map(|(a, b)| a ^ b).collect()
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct FsMetadata {
    // based on https://github.com/openbsd/src/blob/1835b44f319c9f17642bb957cc6602d2762cc3ae/sys/sys/stat.h#L45-L75
    mode: u8,
    birthat: DateTime<Utc>,
    accessat: DateTime<Utc>,
    changeat: DateTime<Utc>,
    modifyat: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct SourceMeta {
    filename: Option<String>,
    stat: Option<FsMetadata>,
    crc32: Option<String>,
    md5sum: Option<String>,
    sha1sum: Option<String>,
    sha224sum: Option<String>,
    sha256sum: Option<String>,
    sha384sum: Option<String>,
    sha512sum: Option<String>,
    sha3_224sum: Option<String>,
    sha3_256sum: Option<String>,
    sha3_384sum: Option<String>,
    sha3_512sum: Option<String>,
    sha3sum: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct Aes256Key {
    version: String,
    cycles: Option<u32>,
    key: String,
    iv: String,
    blob: String,
    sourcemeta: Option<SourceMeta>,
}

// MaGic PreFix
const AESMGPF: [u8; 8] = [0x1f, 0x8b, 0x08, 0x08, 0x61, 0x58, 0x37, 0x65];

fn getcurrentversion() -> String {
    format!("obg-v{}", env!("CARGO_PKG_VERSION"))
}

pub fn match_prefix(magicpfx: &[u8]) -> bool {
    magicpfx.to_vec() == AESMGPF.to_vec()
}
// signs https://github.com/openbsd/src/blob/1835b44f319c9f17642bb957cc6602d2762cc3ae/sys/sys/signal.h#L51-L99

impl Aes256Key {
    pub fn skey(&self) -> B256 {
        let mut skey: B256 = [0x0; 32];
        skey.copy_from_slice(&self.key.as_bytes()[..32]);
        skey
    }
    pub fn siv(&self) -> B128 {
        let mut siv: B128 = [0x0; 16];
        siv.copy_from_slice(&self.iv.as_bytes()[..16]);
        siv
    }
    pub fn with_sourcemeta(&self, meta: SourceMeta) -> Aes256Key {
        let mut result = self.clone();
        result.sourcemeta = Some(meta);
        result
    }
    pub fn new(key: B256, iv: B128, blob: &[u8], cycles: u32) -> Aes256Key {
        Aes256Key {
            key: hex::encode(key),
            iv: hex::encode(iv),
            blob: hex::encode(blob),
            cycles: Some(cycles),
            sourcemeta: None,
            version: getcurrentversion(),
        }
    }
    pub fn new_with_meta(
        key: B256,
        iv: B128,
        blob: &[u8],
        cycles: u32,
        meta: SourceMeta,
    ) -> Aes256Key {
        Aes256Key {
            key: hex::encode(key),
            iv: hex::encode(iv),
            blob: hex::encode(blob),
            cycles: Some(cycles),
            sourcemeta: Some(meta),
            version: getcurrentversion(),
        }
    }
    pub fn derive(
        passwords: Vec<String>,
        password_hwm: u64,
        salts: Vec<String>,
        salt_hwm: u64,
        cycles: u32,
        salt_derivation_scheme: DerivationScheme,
        shuffle_iv: bool,
    ) -> Result<Aes256Key, Error> {
        let mut rng = rand::thread_rng();

        let mut password = Vec::<u8>::new();
        for sec in passwords {
            password.extend(if Path::new(&sec).exists() {
                read_bytes_high_water_mark(&sec, password_hwm)?
            } else {
                sec.as_str().as_bytes().to_vec()
            });
        }

        let mut salt = Vec::<u8>::new();
        for st in salts {
            salt.extend(if Path::new(&st).exists() {
                read_bytes_high_water_mark(&st, salt_hwm)?
            } else {
                st.as_str().as_bytes().to_vec()
            });
        }

        let key = pbkdf2_sha384_256bits(&password, &salt, cycles);
        let blob = pbkdf2_sha512(&password, &salt, cycles, 72);
        let dv = salt_derivation_scheme.derive(&salt, &password, cycles);
        let mut iv = [0; 16];
        iv.copy_from_slice(&dv[..16]);
        if shuffle_iv {
            iv.shuffle(&mut rng);
        }
        Ok(Aes256Key::new(key, iv, &blob, cycles))
    }
    pub fn save_to_yaml_file(&self, filename: String) -> Result<(), Error> {
        let mut file = open_write(&filename)?;
        let yaml = serde_yaml::to_string(self)?;
        Ok(file.write_all(yaml.as_bytes())?)
    }
    pub fn load_from_yaml_file(filename: String) -> Result<Aes256Key, Error> {
        let bytes = read_bytes(&filename)?;
        let key: Aes256Key = serde_yaml::from_slice(&bytes)?;
        Ok(key)
    }
    pub fn load_from_file(
        filename: String,
        strict: bool,
        key_offset: Option<usize>,
        salt_offset: Option<usize>,
        blob_offset: Option<usize>,
        moo: bool,
    ) -> Result<Aes256Key, Error> {
        let bytes = read_bytes(&filename)?;
        let mut ml: usize = 110;
        ml = match key_offset {
            Some(o) => {
                if o > ml {
                    o
                } else {
                    ml
                }
            }
            None => ml,
        };
        ml = match salt_offset {
            Some(o) => {
                if o > ml {
                    o
                } else {
                    ml
                }
            }
            None => ml,
        };
        ml = match blob_offset {
            Some(o) => {
                if o > ml {
                    o
                } else {
                    ml
                }
            }
            None => ml,
        };
        if match moo {
            true => bytes.len() / 2,
            false => bytes.len(),
        } < ml
        {
            return Err(Error::FileSystemError(format!(
                "{} is too small for the set of constraints",
                filename
            )));
        }
        let mut bytes = bytes.to_vec();

        if strict {
            let mag1cpfx = bytes.drain(0..8).collect::<Vec<u8>>();
            assert!(match_prefix(&mag1cpfx));
        }

        let lhs = (match moo {
            true => bytes.len() / 2,
            false => bytes.len(),
        }) - 8
            - match key_offset {
                Some(o) => o,
                None => 0,
            };
        let rhs = match moo {
            true => bytes.len() / 2,
            false => bytes.len(),
        };
        let iv = bytes.drain(lhs..rhs).collect::<Vec<u8>>();
        let lhs = (match moo {
            true => bytes.len() / 2,
            false => bytes.len(),
        }) - 16
            - match salt_offset {
                Some(o) => o,
                None => 0,
            };
        let rhs = match moo {
            true => bytes.len() / 2,
            false => bytes.len(),
        };
        let key = bytes.drain(lhs..rhs).collect::<Vec<u8>>();
        let lhs = (match moo {
            true => bytes.len() / 2,
            false => bytes.len(),
        }) - 72
            - match blob_offset {
                Some(o) => o,
                None => 0,
            };
        let rhs = match moo {
            true => bytes.len() / 2,
            false => bytes.len(),
        };
        let blob = bytes.drain(lhs..rhs).collect::<Vec<u8>>();

        Ok(Aes256Key {
            version: getcurrentversion(),
            key: hex::encode(key),
            blob: hex::encode(blob),
            iv: hex::encode(iv),
            cycles: None,
            sourcemeta: None,
        })
    }
    pub fn save_to_file(&self, filename: String) -> Result<(), Error> {
        let mut file = open_write(&filename)?;
        file.write_all(&AESMGPF.to_vec())?;
        file.write_all(filename.as_str().as_bytes())?;
        file.write_all(&[0x00, 0x00, 0x00, 0x00])?;
        let mut rng = thread_rng();
        let mut mods: Vec<usize> = (237..1283).collect();
        mods.shuffle(&mut rng);
        let len = mods[0];
        let mut buf = Vec::<u8>::new();
        buf.resize(len, 0xa);
        rng.fill_bytes(&mut buf);
        file.write_all(&buf)?;
        file.write_all(&[
            0x00, 0x00, 0x00, 0x10, // 2.
            0x00, 0x00, 0x00, 0x00, // 0.
            0x00, 0x00, 0x00, 0x00,
        ])?; // 0
        file.write_all(&hex::decode("0105161050110a12")?)?;
        file.write_all(&[0x26, 0x7b, 0xfe, 0x0e])?;
        file.write_all(&hex::decode(&format!(
            "{:016x}",
            match self.cycles {
                Some(c) => c,
                None => 0,
            }
        ))?)?;
        file.write_all(&self.skey())?;
        file.write_all(&self.siv())?;
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct Aes256CbcCodec {
    cipher: Aes256,
    key: B256,
    iv: B128,
    padding: Padding,
}

impl Aes256CbcCodec {
    pub fn new(key: B256, iv: B128) -> Aes256CbcCodec {
        let padding = Padding::Ansix923(Ansix923::new(0xff as u8));
        Aes256CbcCodec::new_with_padding(key, iv, padding)
    }
    pub fn new_with_padding(key: B256, iv: B128, padding: Padding) -> Aes256CbcCodec {
        let gkey = GenericArray::from(key);
        Aes256CbcCodec {
            cipher: Aes256::new(&gkey),
            key: key,
            iv: iv,
            padding: padding,
        }
    }
    pub fn new_with_key(key: Aes256Key) -> Aes256CbcCodec {
        let padding = Padding::Ansix923(Ansix923::new(0xff as u8));
        let gkey = key.skey();
        let giv = key.siv();
        Aes256CbcCodec {
            cipher: Aes256::new(&GenericArray::from(gkey)),
            key: gkey,
            iv: giv,
            padding: padding,
        }
    }
    pub fn encrypt_first_block(&self, input_block: &[u8]) -> Vec<u8> {
        self.encrypt_block(input_block, &self.iv)
    }
    pub fn cipher(&self) -> Aes256 {
        Aes256::new(&(self.key).into())
    }
}

impl EncryptionEngine for Aes256CbcCodec {
    fn encrypt_block(&self, plaintext: &[u8], xor_block: &[u8]) -> Vec<u8> {
        // XXX: validate blocks' size to 16 bytes and return Result<Vec<u8>, Error>
        let mut input_block = xor(&plaintext, &xor_block);
        let mut output_block = GenericArray::from_mut_slice(input_block.as_mut_slice());
        self.cipher.encrypt_block(&mut output_block);
        output_block.as_slice().to_vec()
    }
    fn encrypt_blocks(&self, plaintext: &[u8]) -> Vec<u8> {
        let mut result: Vec<Vec<u8>> = Vec::new();
        // split plaintext into 16 blocks
        // let padded = pad128bits_ansi_x923(&plaintext.to_vec());
        // let plaintext = padded.as_slice();
        let chunks: Vec<Vec<u8>> = plaintext.chunks(16).map(|c| c.to_vec()).collect();
        let count = chunks.len();

        for (index, block) in chunks.iter().enumerate() {
            let xor_block = if index == 0 {
                &self.iv
            } else {
                result[index - 1].as_slice()
            };
            let last_block_pos = count - 1;
            let block = &if index == last_block_pos && block.len() < 16 {
                // ensure padding in the last block to avoid side-effects
                self.padding.pad(&block).to_vec()
            } else {
                block.to_vec()
            };
            result.push(self.encrypt_block(block, xor_block));
        }
        let opaque: Vec<u8> = result.iter().flatten().map(|b| b.clone()).collect();
        // let mut ciphertext = Vec::<u8>::new();
        // ciphertext.extend(self.magic_id());
        // ciphertext.extend(opaque);
        // ciphertext
        opaque
    }
    fn decrypt_blocks(&self, ciphertext: &[u8]) -> Vec<u8> {
        let mut result: Vec<Vec<u8>> = Vec::new();
        // split ciphertext into 16 blocks
        let chunks: Vec<Vec<u8>> = ciphertext.chunks(16).map(|c| c.to_vec()).collect();
        let count = chunks.len();
        let last_block_pos = count - 1;

        for (index, block) in chunks.iter().enumerate() {
            let xor_block = if index == 0 {
                &self.iv
            } else {
                chunks[index - 1].as_slice()
            };
            let block = self.decrypt_block(block, xor_block);
            result.push(if index == last_block_pos {
                // ensure padding in the last block to avoid side-effects
                self.padding.unpad(&block)
            } else {
                block
            });
        }
        result.iter().flatten().map(|b| b.clone()).collect()
    }
    fn decrypt_block(&self, ciphertext: &[u8], xor_block: &[u8]) -> Vec<u8> {
        // XXX: validate block size 16 bytes and return Result<Vec<u8>, Error>
        let mut ciphertext = ciphertext.to_vec();
        let mut plaintext = GenericArray::from_mut_slice(ciphertext.as_mut_slice());
        self.cipher.decrypt_block(&mut plaintext);
        xor(&plaintext.as_slice(), &xor_block).to_vec()
    }
}

#[cfg(test)]
mod aes256cbc_tests {
    use crate::aescbc::cdc::{xor_128, Aes256CbcCodec, Aes256Key, EncryptionEngine, B128, B256};
    use crate::aescbc::kd::pbkdf2_sha384_128bits;
    use crate::aescbc::kd::pbkdf2_sha384_256bits;
    use crate::aescbc::kd::DerivationScheme;
    use crate::hashis::CrcAlgo;
    use crate::ioutils::read_bytes;
    use aes::cipher::{generic_array::GenericArray, BlockDecrypt, BlockEncrypt, KeyInit};
    use aes::Aes256;
    use k9::assert_equal;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
    pub struct Block {
        pub plaintext: B128,
        pub input: B128,
        pub output: B128,
        pub ciphertext: B128,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct Aes256CBCTestCase {
        pub key: B256,
        pub iv: B128,
        pub blocks: Vec<Block>,
    }

    impl Aes256CBCTestCase {
        pub fn block_at(&self, index: usize) -> Block {
            self.blocks.get(index).unwrap().clone()
        }
    }

    pub fn nist_cbc_aes256_encryption_test_input() -> Aes256CBCTestCase {
        // https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38a.pdf
        // p.28 - # F.2.5 CBC-AES256.Encrypt Vectors
        let encryption_blocks = [
            Block {
                plaintext: [
                    0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73,
                    0x93, 0x17, 0x2a,
                ],
                input: [
                    0x6b, 0xc0, 0xbc, 0xe1, 0x2a, 0x45, 0x99, 0x91, 0xe1, 0x34, 0x74, 0x1a, 0x7f,
                    0x9e, 0x19, 0x25,
                ],
                output: [
                    0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba, 0x77, 0x9e, 0xab, 0xfb, 0x5f,
                    0x7b, 0xfb, 0xd6,
                ],
                ciphertext: [
                    0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba, 0x77, 0x9e, 0xab, 0xfb, 0x5f,
                    0x7b, 0xfb, 0xd6,
                ],
            },
            Block {
                plaintext: [
                    0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45,
                    0xaf, 0x8e, 0x51,
                ],
                input: [
                    0x5b, 0xa1, 0xc6, 0x53, 0xc8, 0xe6, 0x5d, 0x26, 0xe9, 0x29, 0xc4, 0x57, 0x1a,
                    0xd4, 0x75, 0x87,
                ],
                output: [
                    0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6,
                    0x70, 0x2c, 0x7d,
                ],
                ciphertext: [
                    0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6,
                    0x70, 0x2c, 0x7d,
                ],
            },
            Block {
                plaintext: [
                    0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a,
                    0x0a, 0x52, 0xef,
                ],
                input: [
                    0xac, 0x34, 0x52, 0xd0, 0xdd, 0x87, 0x64, 0x9c, 0x82, 0x64, 0xb6, 0x62, 0xdc,
                    0x7a, 0x7e, 0x92,
                ],
                output: [
                    0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf, 0xa5, 0x30, 0xe2, 0x63, 0x04,
                    0x23, 0x14, 0x61,
                ],
                ciphertext: [
                    0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf, 0xa5, 0x30, 0xe2, 0x63, 0x04,
                    0x23, 0x14, 0x61,
                ],
            },
            Block {
                plaintext: [
                    0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6,
                    0x6c, 0x37, 0x10,
                ],
                input: [
                    0xcf, 0x6d, 0x17, 0x2c, 0x76, 0x96, 0x21, 0xd8, 0x08, 0x1b, 0xa3, 0x18, 0xe2,
                    0x4f, 0x23, 0x71,
                ],
                output: [
                    0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc, 0xda, 0x6c, 0x19, 0x07, 0x8c,
                    0x6a, 0x9d, 0x1b,
                ],
                ciphertext: [
                    0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc, 0xda, 0x6c, 0x19, 0x07, 0x8c,
                    0x6a, 0x9d, 0x1b,
                ],
            },
        ];
        return Aes256CBCTestCase {
            key: [
                0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d,
                0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3,
                0x09, 0x14, 0xdf, 0xf4,
            ],
            iv: [
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
                0x0e, 0x0f,
            ],
            blocks: encryption_blocks.to_vec(),
        };
    }
    pub fn nist_cbc_aes256_decryption_test_input() -> Aes256CBCTestCase {
        // https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38a.pdf
        // p.29 - # F.2.6 CBC-AES256.Decrypt Vectors
        let decryption_blocks = [
            Block {
                ciphertext: [
                    0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba, 0x77, 0x9e, 0xab, 0xfb, 0x5f,
                    0x7b, 0xfb, 0xd6,
                ],
                input: [
                    0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba, 0x77, 0x9e, 0xab, 0xfb, 0x5f,
                    0x7b, 0xfb, 0xd6,
                ],
                output: [
                    0x6b, 0xc0, 0xbc, 0xe1, 0x2a, 0x45, 0x99, 0x91, 0xe1, 0x34, 0x74, 0x1a, 0x7f,
                    0x9e, 0x19, 0x25,
                ],
                plaintext: [
                    0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73,
                    0x93, 0x17, 0x2a,
                ],
            },
            Block {
                ciphertext: [
                    0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6,
                    0x70, 0x2c, 0x7d,
                ],
                input: [
                    0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6,
                    0x70, 0x2c, 0x7d,
                ],
                output: [
                    0x5b, 0xa1, 0xc6, 0x53, 0xc8, 0xe6, 0x5d, 0x26, 0xe9, 0x29, 0xc4, 0x57, 0x1a,
                    0xd4, 0x75, 0x87,
                ],
                plaintext: [
                    0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45,
                    0xaf, 0x8e, 0x51,
                ],
            },
            Block {
                ciphertext: [
                    0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf, 0xa5, 0x30, 0xe2, 0x63, 0x04,
                    0x23, 0x14, 0x61,
                ],
                input: [
                    0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf, 0xa5, 0x30, 0xe2, 0x63, 0x04,
                    0x23, 0x14, 0x61,
                ],
                output: [
                    0xac, 0x34, 0x52, 0xd0, 0xdd, 0x87, 0x64, 0x9c, 0x82, 0x64, 0xb6, 0x62, 0xdc,
                    0x7a, 0x7e, 0x92,
                ],
                plaintext: [
                    0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a,
                    0x0a, 0x52, 0xef,
                ],
            },
            Block {
                ciphertext: [
                    0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc, 0xda, 0x6c, 0x19, 0x07, 0x8c,
                    0x6a, 0x9d, 0x1b,
                ],
                input: [
                    0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc, 0xda, 0x6c, 0x19, 0x07, 0x8c,
                    0x6a, 0x9d, 0x1b,
                ],
                output: [
                    0xcf, 0x6d, 0x17, 0x2c, 0x76, 0x96, 0x21, 0xd8, 0x08, 0x1b, 0xa3, 0x18, 0xe2,
                    0x4f, 0x23, 0x71,
                ],
                plaintext: [
                    0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6,
                    0x6c, 0x37, 0x10,
                ],
            },
        ];
        return Aes256CBCTestCase {
            key: [
                0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d,
                0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3,
                0x09, 0x14, 0xdf, 0xf4,
            ],
            iv: [
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
                0x0e, 0x0f,
            ],
            blocks: decryption_blocks.to_vec(),
        };
    }

    #[test]
    pub fn test_confirm_cbc_aes256_nist_spec_encrypt_single_block() {
        // Given the CBC-AES256 encryption input provided by NIST's Special Publication 800-38A 2001 Edition (p.28)
        let encryption_input = nist_cbc_aes256_encryption_test_input();

        // When I initialize the low-level implementation of the aes crate
        let key = GenericArray::from(encryption_input.key);
        let iv = encryption_input.iv.clone();
        let cipher = Aes256::new(&key);

        // And I take the block #1 of NIST's input, plaintext and IV
        let block1 = encryption_input.block_at(0);
        let block1_plaintext = block1.plaintext.clone();

        // And I XOR the block's plaintext with the IV
        let xor_input = xor_128(block1_plaintext, iv);

        // Then it should match the input
        assert_equal!(xor_input, block1.input);

        let mut block1_input = GenericArray::from(block1.input);

        // And I clone the original block input
        let block1_input_copy = block1_input.clone();

        // When I encrypt the Block #1's input in-place
        cipher.encrypt_block(&mut block1_input);

        // Then it should match the Block #1's ciphertext
        assert_equal!(
            block1_input,
            GenericArray::from(encryption_input.blocks[0].ciphertext)
        );

        // And it should also match the Block #1's output
        assert_equal!(
            block1_input,
            GenericArray::from(encryption_input.blocks[0].output)
        );

        // When I then decrypt the block in-place
        cipher.decrypt_block(&mut block1_input);

        // Then it should match the Block #1's input
        assert_equal!(
            block1_input,
            GenericArray::from(encryption_input.blocks[0].input)
        );

        // And it should match the cloned input
        assert_equal!(block1_input, block1_input_copy);
    }

    #[test]
    pub fn test_confirm_cbc_aes256_nist_spec_decrypt_single_block() {
        // Given the CBC-AES256 decryption input provided by NIST's Special Publication 800-38A 2001 Edition (p.28)
        let decryption_input = nist_cbc_aes256_decryption_test_input();

        // When I initialize the low-level implementation of the aes crate
        let key = GenericArray::from(decryption_input.key);
        let iv = decryption_input.iv.clone();
        let cipher = Aes256::new(&key);

        // And I take the block #1 of NIST's input, plaintext and IV
        let block1 = decryption_input.block_at(0);
        let block1_output = block1.output.clone();

        // And I XOR the block's output with the IV
        let xor_output = xor_128(block1_output, iv);

        // Then it should match the plaintext
        assert_equal!(xor_output, block1.plaintext);

        let mut block1_input = GenericArray::from(block1.input);

        // And I clone the original block input
        let block1_input_copy = block1_input.clone();

        // When I decrypt the Block #1's input in-place
        cipher.decrypt_block(&mut block1_input);

        // Then it should match the Block #1's output
        assert_equal!(
            block1_input,
            GenericArray::from(decryption_input.blocks[0].output)
        );

        // And it should match the Block #1's plaintext XOR IV
        assert_equal!(
            block1_input,
            GenericArray::from(xor_128(decryption_input.blocks[0].plaintext, iv))
        );

        // When I then encrypt the block in-place
        cipher.encrypt_block(&mut block1_input);

        // Then it should match the Block #1's input
        assert_equal!(
            block1_input,
            GenericArray::from(decryption_input.blocks[0].input)
        );

        // And it should match the cloned input
        assert_equal!(block1_input, block1_input_copy);
    }

    #[test]
    pub fn test_codec_encrypt_first_block() {
        // Given the CBC-AES256 encryption input provided by NIST's Special Publication 800-38A 2001 Edition (p.28)
        let encryption_input = nist_cbc_aes256_encryption_test_input();

        // And I initialize the Aes256CbcCodec with the key and iv
        let cdc = Aes256CbcCodec::new(encryption_input.key, encryption_input.iv);

        // And I take the block #1 of NIST's input data
        let block1 = encryption_input.block_at(0);

        // When I encrypt the first Block #1's plaintext
        let encrypted_ptf = cdc.encrypt_first_block(&block1.plaintext);

        // And I encrypt the first Block #1's input with the IV as XOR block
        let encrypted_ptx = cdc.encrypt_block(&block1.plaintext, &cdc.iv);

        // Then the plaintext encrypted as "first block" should match the Block #1's ciphertext
        assert_equal!(encrypted_ptf, block1.ciphertext.to_vec());

        // And the plaintext encrypted with the IV as "XOR block" should match the Block #1's ciphertext
        assert_equal!(encrypted_ptx, block1.ciphertext.to_vec());

        // And the plaintext encrypted as "first block" should match the Block #1's output
        assert_equal!(encrypted_ptf, block1.output.to_vec());

        // And the plaintext encrypted with the IV as "XOR block" should match the Block #1's output
        assert_equal!(encrypted_ptx, block1.output.to_vec());

        // When I then decrypt ciphertext with the IV as "XOR block"
        let decrypted_ct = cdc.decrypt_block(&block1.ciphertext, &cdc.iv);

        // Then it should match the Block #1's plaintext
        assert_equal!(decrypted_ct, block1.plaintext);

        // Then it should match the Block #1's plaintext XOR IV
        assert_equal!(decrypted_ct, xor_128(block1.input, cdc.iv));
    }

    #[test]
    pub fn test_codec_decrypt_first_block() {
        // Given the CBC-AES256 decryption input provided by NIST's Special Publication 800-38A 2001 Edition (p.28)
        let decryption_input = nist_cbc_aes256_decryption_test_input();

        // And I initialize the Aes256CbcCodec with the key and iv
        let cdc = Aes256CbcCodec::new(decryption_input.key, decryption_input.iv);

        // And I take the block #1 of NIST's input data
        let block1 = decryption_input.block_at(0);

        // When I decrypt the first Block #1's input with the IV as XOR block
        let decrypted_ptx = cdc.decrypt_block(&block1.ciphertext, &decryption_input.iv);

        // And I decrypt the first Block #1's input with an zero-filled slice as XOR block
        let empty_mask = [0u8; 16];
        let decrypted_ptz = cdc.decrypt_block(&block1.ciphertext, &empty_mask);

        // Then the plaintext decrypted with the IV as "XOR block" should match the Block #1's ciphertext
        assert_equal!(decrypted_ptx, block1.plaintext.to_vec());

        // And the plaintext decrypted with the empty mark as "XOR block" should match the Block #1's output
        assert_equal!(decrypted_ptz, block1.output.to_vec());

        // When I then encrypt plaintext with the IV as "XOR block"
        let encrypted_pt = cdc.encrypt_block(&block1.plaintext, &decryption_input.iv);

        // Then it should match the Block #1's ciphertext
        assert_equal!(encrypted_pt, block1.ciphertext);

        // And it should match the Block #1's ciphertext
        assert_equal!(encrypted_pt, block1.ciphertext);
    }

    #[test]
    pub fn test_codec_aes256_cbc_transcript_nist_spec_encrypt_four_blocks() {
        // Given the CBC-AES256 encryption input provided by NIST's Special Publication 800-38A 2001 Edition (p.28)
        let encryption_input = nist_cbc_aes256_encryption_test_input();

        // And I initialize the Aes256CbcCodec with the key and iv
        let cdc = Aes256CbcCodec::new(encryption_input.key, encryption_input.iv);

        // And I combine all 4 blocks of plaintext and ciphertext into a single block
        let expected_plaintext: Vec<u8> = encryption_input
            .blocks
            .iter()
            .map(|b| b.plaintext)
            .flatten()
            .collect();

        let expected_ciphertext: Vec<u8> = encryption_input
            .blocks
            .iter()
            .map(|b| b.ciphertext)
            .flatten()
            .collect();

        // When I encrypt the combined plaintext
        let ciphertext = cdc.encrypt_blocks(&expected_plaintext);
        // Then the result should match the combined ciphertext
        assert_equal!(ciphertext, expected_ciphertext);

        // When I decrypt the ciphertext
        let plaintext = cdc.decrypt_blocks(&ciphertext);
        // Then the result should match the combined plaintext
        assert_equal!(plaintext, expected_plaintext);
    }

    #[test]
    pub fn test_codec_aes256_cbc_transcript_arbitraryly_sized_buffer() {
        // Background: I have a key and IV
        let key = [71u8; 32];
        let iv = [84u8; 16];

        // Background: There is a buffer whose length has a remainder with modulus 16
        let plaintext = read_bytes("tests/plaintext.jpg").unwrap();
        let plaintext_length = plaintext.len();

        // Given I initialize a Aes256CbcCodec with a key and IV
        let cdc = Aes256CbcCodec::new(key, iv);

        // When I encrypt the combined plaintext
        let ciphertext = cdc.encrypt_blocks(&plaintext);

        // And subsequently decrypt that ciphertext
        let decrypted = cdc.decrypt_blocks(&ciphertext);

        // Then the result should match the original plaintext
        assert_equal!(decrypted.len() - plaintext_length, 0);
        assert_equal!(decrypted.len(), plaintext_length);
        assert_equal!(plaintext, decrypted);
    }
    #[test]
    pub fn test_codec_aes256_cbc_encrypt_pbkdf2_key_and_iv() {
        // Background: I have a key and IV
        let key = pbkdf2_sha384_256bits(b"cypher where is tank?", b"soul society", 83);
        let iv = pbkdf2_sha384_128bits(b"84 + 4(vier(six-he/saw him/vejo ele/vejo him/vejo rim(kidney - human organ that processes fear))((fear / four + fe' ar + avatar))) == X == ascii code 88", b"GO = 'George Orwell' = 4 in japanese. O shit we're back on fear...", 88); // XXX rs

        // Background: There is a buffer whose length has a remainder with modulus 16
        let plaintext = read_bytes("tests/plaintext.jpg").unwrap();
        let plaintext_length = plaintext.len();

        // Given I initialize a Aes256CbcCodec with a key and IV
        let cdc = Aes256CbcCodec::new(key, iv);

        // When I encrypt the combined plaintext
        let ciphertext = cdc.encrypt_blocks(&plaintext);

        // And subsequently decrypt that ciphertext
        let decrypted = cdc.decrypt_blocks(&ciphertext);

        // Then the result should match the original plaintext
        assert_equal!(decrypted.len() - plaintext_length, 0);
        assert_equal!(decrypted.len(), plaintext_length);
        assert_equal!(plaintext, decrypted);
    }
    #[test]
    pub fn test_codec_aes256_cbc_encrypt_derive() {
        // Background: I have a Aes256Key
        let password = "cypher where is tank?".to_string();
        let salt = "soul society".to_string();
        let key = Aes256Key::derive(
            [password].to_vec(),
            u64::MAX,
            [salt].to_vec(),
            u64::MAX,
            0x35,
            DerivationScheme::Crc(CrcAlgo::GcRc256),
            false,
        )
        .expect("it appears that the key cannot be derived in this instant");

        // Background: There is a buffer whose length has a remainder with modulus 16
        let plaintext = read_bytes("tests/plaintext.jpg").unwrap();
        let plaintext_length = plaintext.len();

        // Given I initialize a Aes256CbcCodec with a Aes256Key
        let cdc = Aes256CbcCodec::new_with_key(key);

        // When I encrypt the combined plaintext
        let ciphertext = cdc.encrypt_blocks(&plaintext);

        // And subsequently decrypt that ciphertext
        let decrypted = cdc.decrypt_blocks(&ciphertext);

        // Then the result should match the original plaintext
        assert_equal!(decrypted.len() - plaintext_length, 0);
        assert_equal!(decrypted.len(), plaintext_length);
        assert_equal!(plaintext, decrypted);
    }
}