encodex 0.2.0

Implementation of and cryptanalysis tool for legacy and modern codes, ciphers and hashes.
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
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
// Copyright (C) 2023  Fabian Moos
// This file is part of encodex.
//
// encodex is free software: you can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// encodex is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with encodex. If not,
// see <https://www.gnu.org/licenses/>.
//

//! Functionality for handling [base64](Base64Context) codes.

use std::collections::hash_map::HashMap;

use crate::{
    AtomClass,
    AtomType,
    CaseInsensitiveCiphertext,
    code::{
        Code,
        Decode,
        Encode,
    },
    CryptoError,
    CryptographicAtom,
    map,
};

use super::{
    base64_decode,
    base64_encode,
};



/// [`CryptographicAtom`] for handling [base64](Base64Context) plain- and ciphertexts.
///
/// The prefix `B64*` is used for [base64](Base64Context) strings in documentation comments.
///
/// # Usage Example
///
/// ```
/// use encodex::code::base_encoding::Base64Context;
/// use encodex::code::Encode;
///
/// let mut ctx = Base64Context::new();
/// let plaintext = "This string will not produce any padding bytes!".to_string().into_bytes();
/// let expected_ciphertext = "VGhpcyBzdHJpbmcgd2lsbCBub3QgcH\
///                            JvZHVjZSBhbnkgcGFkZGluZyBieXRl\
///                            cyE=".to_string().into_bytes();
///
/// assert_eq![ctx.encode(&plaintext), Ok(expected_ciphertext)];
/// ```
///
/// # Plaintext
///
/// Every byte stream can be a [base64](Base64Context) plaintext.
///
/// # Ciphertext
///
/// Usually base encodings are used in situations when some special bytes can lead to errors while
/// `ASCII` letters, numbers, `+` and `/` are fine. As a result only byte vectors containing only
/// bytes from the table below are valid ciphertexts. All other byte vectors will be rejected by a
/// [`Base64Context`].
///
/// The last byte or the last two bytes of the ciphertext may be `=`.
///
/// # Alphabet
///
/// The following table shows the alphabet that is used by the [base64](Base64Context) code. The
/// first row and first column are the index, and the cell where a column and a row cross each other
/// is the corresponding cipher value. See the Encode section below for an explanation on how the
/// ciphertext is calculated.
///
/// |         || 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | a | b | c | d | e | f |
/// |---------||---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
/// | **0x0** ||`A`|`B`|`C`|`D`|`E`|`F`|`G`|`H`|`I`|`J`|`K`|`L`|`M`|`N`|`O`|`P`|
/// | **0x1** ||`Q`|`R`|`S`|`T`|`U`|`V`|`W`|`X`|`Y`|`Z`|`a`|`b`|`c`|`d`|`e`|`f`|
/// | **0x2** ||`g`|`h`|`i`|`j`|`k`|`l`|`m`|`n`|`o`|`p`|`q`|`r`|`s`|`t`|`u`|`v`|
/// | **0x3** ||`w`|`x`|`y`|`z`|`0`|`1`|`2`|`3`|`4`|`5`|`6`|`7`|`8`|`9`|`+`|`/`|
/// | **0x4** ||`=`|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
///
/// # Algorithm
///
/// ## Encode
///
/// 1. The byte stream is separated into `6 bit` blocks.
/// 2. It is clear that every `6 bit` block can have `2^6` = `64` different values. The alphabet
///    table can be used to determine the corresponding ***Base64*** value for every `6 bit` block.
///    This can be implemented as an array containing all values from the table.
///
/// The last value in the alphabet table is the padding byte that will be appended if the number of
/// bytes in the plaintext is not a multiple of `4`.
///
/// ## Decode
///
/// 1. Take a character from the ciphertext and replace it with its index from the alphabet table,
///    using only `6 bits` to represent the resulting value.
/// 2. Append exactly the `6 bits` from step 1 to the plaintext.
/// 3. Repeat.
///
/// All padding bytes `=` are ignored in the decode algorithm.
#[derive(Clone, Copy)]
pub struct Base64Context {
    /// The [class](AtomClass) this [`CryptographicAtom`] belongs to.
    atom_class: AtomClass,
    /// The [type](AtomType) of every instance of this [`CryptographicAtom`].
    atom_type: AtomType,
}

impl Base64Context {
    /// Returns the decode alphabet as a [`HashMap`].
    ///
    /// The returned [`HashMap`] maps every ciphertext value to its corresponding `6 bit` index in
    /// [base64](Base64Context) alphabet. The padding byte `=` is mapped to `0x40`.
    fn get_decode_alphabet() -> HashMap<u8, u32> {
        map![
            (0x41, 0), (0x42, 1), (0x43, 2), (0x44, 3),
            (0x45, 4), (0x46, 5), (0x47, 6), (0x48, 7),
            (0x49, 8), (0x4a, 9), (0x4b, 10), (0x4c, 11),
            (0x4d, 12), (0x4e, 13), (0x4f, 14), (0x50, 15),
            (0x51, 16), (0x52, 17), (0x53, 18), (0x54, 19),
            (0x55, 20), (0x56, 21), (0x57, 22), (0x58, 23),
            (0x59, 24), (0x5a, 25), (0x61, 26), (0x62, 27),
            (0x63, 28), (0x64, 29), (0x65, 30), (0x66, 31),
            (0x67, 32), (0x68, 33), (0x69, 34), (0x6a, 35),
            (0x6b, 36), (0x6c, 37), (0x6d, 38), (0x6e, 39),
            (0x6f, 40), (0x70, 41), (0x71, 42), (0x72, 43),
            (0x73, 44), (0x74, 45), (0x75, 46), (0x76, 47),
            (0x77, 48), (0x78, 49), (0x79, 50), (0x7a, 51),
            (0x30, 52), (0x31, 53), (0x32, 54), (0x33, 55),
            (0x34, 56), (0x35, 57), (0x36, 58), (0x37, 59),
            (0x38, 60), (0x39, 61), (0x2b, 62), (0x2f, 63),
            (0x3d, 64)
        ]
    }

    /// Returns the encode alphabet as an array.
    ///
    /// Any `6 bit` block entered into the returned array will immediately return the corresponding
    /// ciphertext value. For `0x40` the padding byte `=` will be returned.
    fn get_encode_alphabet() -> [u8; 65] {
        [
            0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
            0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,
            0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
            0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
            0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e,
            0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,
            0x77, 0x78, 0x79, 0x7a, 0x30, 0x31, 0x32, 0x33,
            0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2b, 0x2f,
            0x3d
        ]
    }

    /// Returns a new [`Base64Context`] [`CryptographicAtom`].
    pub fn new() -> Base64Context {
        Base64Context {
            atom_class: AtomClass::Code,
            atom_type: AtomType::Base64,
        }
    }

    /// Validates the given ciphertext.
    ///
    /// If the given ciphertext does not match the constraints for [base64](Base64Context)
    /// ciphertexts, an [error](CryptoError) is returned.
    fn validate_ciphertext(
        ciphertext: &Vec<u8>,
    ) -> Result<(), CryptoError> {
        let length = ciphertext.len();

        if length % 4 != 0 {
            return Err(CryptoError::IllegalResidueClass(
                "Failure during Base64 ciphertext validation!".to_string(),
                (ciphertext.len() % 4) as u8, 4,
            ));
        }

        let alphabet = Base64Context::get_decode_alphabet();
        let padding_byte = Base64Context::get_encode_alphabet()[64];
        let mut second_last_byte_is_padding = false;
        let mut i = 0;

        for c in ciphertext {
            if i < length - 2 && (!alphabet.contains_key(c) || *c == padding_byte) {
                return Err(CryptoError::IllegalCharacter(
                    "Failure during Base64 ciphertext validation!".to_string(), i,
                    ciphertext.clone(),
                ));
            } else if i == length - 2 {
                if !alphabet.contains_key(c) {
                    return Err(CryptoError::IllegalCharacter(
                        "Failure during Base64 ciphertext validation!".to_string(), i,
                        ciphertext.clone(),
                    ));
                } else {
                    second_last_byte_is_padding = *ciphertext.get(i).unwrap() == padding_byte;
                }
            } else {
                if !alphabet.contains_key(c) {
                    return Err(CryptoError::IllegalCharacter(
                        "Failure during Base64 ciphertext validation!".to_string(), i,
                        ciphertext.clone(),
                    ));
                } else if second_last_byte_is_padding
                    && *ciphertext.get(i).unwrap() != padding_byte {
                    return Err(CryptoError::MalformedPadding(
                        "Failure during Base64 ciphertext validation!".to_string(),
                        ciphertext.clone(),
                    ));
                }
            }
            i += 1;
        }

        Ok(())
    }
}

impl CaseInsensitiveCiphertext for Base64Context {
    /// Required by trait [`CryptographicAtom`].
    ///
    /// This trait must be implemented, but always returns [`None`] for this [`CryptographicAtom`],
    /// because a [`Base64Context`] is case sensitive.
    fn ciphertext_is_capitalized(&self) -> Option<bool> { None }

    /// Required by trait [`CryptographicAtom`].
    ///
    /// This trait must be implemented, but does nothing for this [`CryptographicAtom`], because
    /// [`Base64Context`] is case sensitive.
    fn set_ciphertext_capitalization(&mut self, _capitalized: bool) {}
}

impl Code for Base64Context {}

impl CryptographicAtom for Base64Context {
    /// Returns the [class](AtomClass) the [`Base64Context`] belongs to.
    fn get_atom_class(&self) -> AtomClass { self.atom_class }

    /// Returns the [type](AtomType) of a [`Base64Context`].
    fn get_atom_type(&self) -> AtomType { self.atom_type }
}

impl Decode for Base64Context {
    /// Decodes the given ciphertext.
    ///
    /// # Errors
    ///
    /// Returns an error if
    ///
    /// * the ciphertext contains an illegal character,
    /// * the padding is malformed.
    fn decode(
        &mut self,
        ciphertext: &Vec<u8>,
    ) -> Result<Vec<u8>, CryptoError> {
        if let Err(error) = Base64Context::validate_ciphertext(ciphertext) {
            Err(error)
        } else {
            Ok(base64_decode(ciphertext, Base64Context::get_decode_alphabet()))
        }
    }
}

impl Encode for Base64Context {
    /// Encodes the given plaintext.
    fn encode(
        &mut self,
        plaintext: &Vec<u8>,
    ) -> Result<Vec<u8>, CryptoError> {
        Ok(base64_encode(plaintext, Base64Context::get_encode_alphabet()))
    }
}



/// Test vectors for the [base64](Base64Context) code.
///
/// Some of the tests have been taken from `RFC 4648`. Additional tests have been added to increase
/// data coverage, especially edge cases.
#[cfg(any(test, feature = "doc_tests"))]
mod tests {
    use super::*;

    /// Tests the [`get_atom_class`](Base64Context::get_atom_class) method of the [`Base64Context`]
    /// struct.
    ///
    /// This method **must** return [`Code`](AtomClass::Code).
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_01() {
        let ctx = Base64Context::new();
        assert_eq![ctx.get_atom_class(), AtomClass::Code];
    }

    /// Tests the [`get_atom_type`](Base64Context::get_atom_type) method of the [`Base64Context`]
    /// struct.
    ///
    /// This method **must** return [`Base64`](AtomType::Base64).
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_02() {
        let ctx = Base64Context::new();
        assert_eq![ctx.get_atom_type(), AtomType::Base64];
    }

    /// Tests the [`ciphertext_is_capitalized`](Base64Context::ciphertext_is_capitalized) method.
    ///
    /// This method **must** return [`None`].
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_03() {
        let ctx = Base64Context::new();
        assert_eq![ctx.ciphertext_is_capitalized(), None];
    }

    /// Tests the [`set_ciphertext_capitalization`](Base64Context::set_ciphertext_capitalization)
    /// method.
    ///
    /// After setting the capitalization mode to `true`
    /// [`ciphertext_is_capitalized`](Base64Context::ciphertext_is_capitalized) **must** return
    /// [`None`].
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_04() {
        let mut ctx = Base64Context::new();
        ctx.set_ciphertext_capitalization(true);
        assert_eq![ctx.ciphertext_is_capitalized(), None];
    }

    /// Tests the [`set_ciphertext_capitalization`](Base64Context::set_ciphertext_capitalization)
    /// method.
    ///
    /// After setting the capitalization mode to `false`
    /// [`ciphertext_is_capitalized`](Base64Context::ciphertext_is_capitalized) **must** return
    /// [`None`].
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_05() {
        let mut ctx = Base64Context::new();
        ctx.set_ciphertext_capitalization(false);
        assert_eq![ctx.ciphertext_is_capitalized(), None];
    }

    /// Test vector from `RFC 4648` for the [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*`
    ///
    /// Plaintext: `<empty byte array>`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_06() {
        let ciphertext = vec![];
        let expected_plaintext = vec![];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Test vector from `RFC 4648` for the [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*Zg= =`
    ///
    /// Plaintext: `f`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_07() {
        let ciphertext = vec![0x5a, 0x67, 0x3d, 0x3d];
        let expected_plaintext = vec![0x66];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Test vector from `RFC 4648` for the [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*Zm8 =`
    ///
    /// Plaintext: `fo`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_08() {
        let ciphertext = vec![0x5a, 0x6d, 0x38, 0x3d];
        let expected_plaintext = vec![0x66, 0x6f];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Test vector from `RFC 4648` for the [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*Zm9 v`
    ///
    /// Plaintext: `fo`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_09() {
        let ciphertext = vec![0x5a, 0x6d, 0x39, 0x76];
        let expected_plaintext = vec![0x66, 0x6f, 0x6f];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Test vector from `RFC 4648` for the [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*Zm9 vYg ==`
    ///
    /// Plaintext: `foob`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_10() {
        let ciphertext = vec![0x5a, 0x6d, 0x39, 0x76, 0x59, 0x67, 0x3d, 0x3d];
        let expected_plaintext = vec![0x66, 0x6f, 0x6f, 0x62];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Test vector from `RFC 4648` for the [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*Zm9 vYm E=`
    ///
    /// Plaintext: `fooba`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_11() {
        let ciphertext = vec![0x5a, 0x6d, 0x39, 0x76, 0x59, 0x6d, 0x45, 0x3d];
        let expected_plaintext = vec![0x66, 0x6f, 0x6f, 0x62, 0x61];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Test vector from `RFC 4648` for the [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*Zm9 vYm Fy`
    ///
    /// Plaintext: `foobar`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_12() {
        let ciphertext = vec![0x5a, 0x6d, 0x39, 0x76, 0x59, 0x6d, 0x46, 0x79];
        let expected_plaintext = vec![0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Additional test vector for the [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*aA= =`
    ///
    /// Plaintext: `h`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_13() {
        let ciphertext = vec![0x61, 0x41, 0x3d, 0x3d];
        let expected_plaintext = vec![0x68];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Additional test for testing the decoding of numbers and the two special symbols for the
    /// [`decode`](Base64Context::decode) method.
    ///
    /// Ciphertext: `B64*44G /44 G+`
    ///
    /// Plaintext: `みま`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_14() {
        let ciphertext = vec![0x34, 0x34, 0x47, 0x2f, 0x34, 0x34, 0x47, 0x2b];
        let expected_plaintext = vec![0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xbe];

        let mut ctx = Base64Context::new();
        let plaintext = ctx.decode(&ciphertext);

        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Test vector from `RFC 4648` for the [`encode`](Base64Context::encode) method.
    ///
    /// Plaintext: `<empty byte array>`
    ///
    /// Ciphertext: `B64*`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_15() {
        let plaintext = vec![];
        let expected_ciphertext = vec![];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Test vector from `RFC 4648` for the [`encode`](Base64Context::encode) method.
    ///
    /// Plaintext: `f`
    ///
    /// Ciphertext: `B64*Zg= =`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_16() {
        let plaintext = vec![0x66];
        let expected_ciphertext = vec![0x5a, 0x67, 0x3d, 0x3d];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Test vector from `RFC 4648` for the [`encode`](Base64Context::encode) method.
    ///
    /// Plaintext: `fo`
    ///
    /// Ciphertext: `B64*Zm8 =`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_17() {
        let plaintext = vec![0x66, 0x6f];
        let expected_ciphertext = vec![0x5a, 0x6d, 0x38, 0x3d];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Test vector from `RFC 4648` for the [`encode`](Base64Context::encode) method.
    ///
    /// Plaintext: `foo`
    ///
    /// Ciphertext: `B64*Zm9 v`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_18() {
        let plaintext = vec![0x66, 0x6f, 0x6f];
        let expected_ciphertext = vec![0x5a, 0x6d, 0x39, 0x76];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Test vector from `RFC 4648` for the [`encode`](Base64Context::encode) method.
    ///
    /// Plaintext: `foob`
    ///
    /// Ciphertext: `B64*Zm9 vYg ==`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_19() {
        let plaintext = vec![0x66, 0x6f, 0x6f, 0x62];
        let expected_ciphertext = vec![0x5a, 0x6d, 0x39, 0x76, 0x59, 0x67, 0x3d, 0x3d];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Test vector from `RFC 4648` for the [`encode`](Base64Context::encode) method.
    ///
    /// Plaintext: `fooba`
    ///
    /// Ciphertext: `B64*Zm9 vYm E=`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_20() {
        let plaintext = vec![0x66, 0x6f, 0x6f, 0x62, 0x61];
        let expected_ciphertext = vec![0x5a, 0x6d, 0x39, 0x76, 0x59, 0x6d, 0x45, 0x3d];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Test vector from `RFC 4648` for the [`encode`](Base64Context::encode) method.
    ///
    /// Plaintext: `foobar`
    ///
    /// Ciphertext: `B64*Zm9 vYm Fy`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_21() {
        let plaintext = vec![0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72];
        let expected_ciphertext = vec![0x5a, 0x6d, 0x39, 0x76, 0x59, 0x6d, 0x46, 0x79];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Tests the block preparation for-loop of the [`encode`](Base64Context::encode) method.
    ///
    /// This is the loop that prepares the next 3-byte-block for encoding.
    ///
    /// Plaintext: `h`
    ///
    /// ```
    /// //                   h = 0b   0110'1000
    /// // (add padding bytes) = 0b   011010 000000 000000 000000
    /// //  (into hex numbers) = 0x   1a     00     100    100
    /// //          (Base64()) = B64* a      A      =      =
    /// ```
    ///
    /// Ciphertext: `B64*aA= =`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_22() {
        let plaintext = vec![0x68];
        let expected_ciphertext = vec![0x61, 0x41, 0x3d, 0x3d];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Additional test for the [`encode`](Base64Context::encode) method that produces some numbers
    /// and also the additional symbols `/` abd `+` in the output.
    ///
    /// Plaintext: `みま`
    ///
    /// ```
    /// //             みま = 0x        3      0    7       f          3      0    7       e
    /// //   (into binary) = 0b        0011   00 0001   11 1111       0011   00'0001   11'1110
    /// //    (into UTF-8) = 0b   1110'0011 1000'0001 1011'1111  1110'0011 1000'0001 1011'1110
    /// // (separate into
    /// //      (into hex) = 0x   e3        81        bf         e3        81        be
    /// //   6-bit blocks) = 0b   11'1000 11'1000 00'0110 11'1111 11'1000 11'1000 00'0110 11'1110
    /// //      (into hex) = 0x   38      38      06      3f      38      38      06      3e
    /// //      (Base64()) = B64* 4       4       G       /       4       4       G       +
    /// ```
    ///
    /// Ciphertext: `B64*44G /44 G+`
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_23() {
        let plaintext = vec![0xe3, 0x81, 0xbf, 0xe3, 0x81, 0xbe];
        let expected_ciphertext = vec![0x34, 0x34, 0x47, 0x2f, 0x34, 0x34, 0x47, 0x2b];

        let mut ctx = Base64Context::new();
        let ciphertext = ctx.encode(&plaintext);

        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Tests the [`Base64Context`] [`get_decode_alphabet`](Base64Context::get_decode_alphabet)
    /// associated function.
    ///
    /// This test is meant as a friendly reminder, if the [`Base64Context`] code will ever be
    /// changed.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_24() {
        let mut decode_alphabet: HashMap<u8, u32> = HashMap::new();

        let mut k = 0x40;
        for v in 0..=25 {
            k += 1;
            decode_alphabet.insert(k, v);
        }

        k = 0x60;
        for v in 26..=51 {
            k += 1;
            decode_alphabet.insert(k, v);
        }

        k = 0x2f;
        for v in 52..=61 {
            k += 1;
            decode_alphabet.insert(k, v);
        }

        decode_alphabet.insert(0x2b, 62);
        decode_alphabet.insert(0x2f, 63);
        decode_alphabet.insert(0x3d, 64);

        assert_eq![Base64Context::get_decode_alphabet().len(), decode_alphabet.len()];
        assert_eq![Base64Context::get_decode_alphabet(), decode_alphabet];
    }

    /// Tests the [`Base64Context`] [`get_encode_alphabet`](Base64Context::get_encode_alphabet)
    /// associated function.
    ///
    /// This test is meant as a friendly reminder, if the [`Base64Context`] code will ever be
    /// changed.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_25() {
        let mut encode_alphabet: [u8; 65] = [0; 65];

        let mut k = 0;
        for v in 0x41..=0x5a {
            encode_alphabet[k] = v;
            k += 1;
        }
        for v in 0x61..=0x7a {
            encode_alphabet[k] = v;
            k += 1;
        }
        for v in 0x30..=0x39 {
            encode_alphabet[k] = v;
            k += 1;
        }
        encode_alphabet[k] = 0x2b;
        k += 1;
        encode_alphabet[k] = 0x2f;
        k += 1;
        encode_alphabet[k] = 0x3d;

        assert_eq![Base64Context::get_encode_alphabet().len(), encode_alphabet.len()];
        assert_eq![Base64Context::get_encode_alphabet(), encode_alphabet];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating an empty string [base64](Base64Context) ciphertext **must** succeed.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_26() {
        let ciphertext = vec![];
        assert_eq![Base64Context::validate_ciphertext(&ciphertext), Ok(())];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext that contains no padding bytes `=` **must**
    /// succeed.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_27() {
        let ciphertext = vec![0x41, 0x42, 0x43, 0x44];
        assert_eq![Base64Context::validate_ciphertext(&ciphertext), Ok(())];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext that contains exactly one padding byte `=`
    /// **must** succeed.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_28() {
        let ciphertext = vec![0x56, 0x57, 0x58, 0x3d];
        assert_eq![Base64Context::validate_ciphertext(&ciphertext), Ok(())];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext with exactly two padding bytes `=` **must**
    /// succeed.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_29() {
        let ciphertext = vec![0x59, 0x5a, 0x3d, 0x3d];
        assert_eq![Base64Context::validate_ciphertext(&ciphertext), Ok(())];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext that has a wrong residue class **must**
    /// fail.
    ///
    /// Only one test is required because all wrong residue class errors are handled by the same
    /// branch in the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated
    /// function.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_30() {
        let ciphertext = vec![0x41, 0x42];
        assert_eq![
            Base64Context::validate_ciphertext(&ciphertext), Err(CryptoError::IllegalResidueClass(
                "Failure during Base64 ciphertext validation!".to_string(), 2, 4,
            ))
        ];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext that contains a character that is not part
    /// of the [base64](Base64Context) alphabet and is not on the second last or last position of
    /// the ciphertext **must** fail.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_31() {
        let ciphertext = vec![0x45, 0x40, 0x46, 0x47];
        assert_eq![
            Base64Context::validate_ciphertext(&ciphertext), Err(CryptoError::IllegalCharacter(
                "Failure during Base64 ciphertext validation!".to_string(), 1,
                ciphertext,
            ))
        ];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext that contains a character that is not part
    /// of the [base64](Base64Context) alphabet and is on the second last position of the
    /// ciphertext **must** fail.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_32() {
        let ciphertext = vec![0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x3a, 0x3d];
        assert_eq![
            Base64Context::validate_ciphertext(&ciphertext), Err(CryptoError::IllegalCharacter(
                "Failure during Base64 ciphertext validation!".to_string(), 6,
                ciphertext,
            ))
        ];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext that contains padding bytes `=` before the
    /// second last position **must** fail.
    ///
    /// This is independent from the last byte and second last byte tests, because it is an
    /// independent branch in the [`validate_ciphertext`](Base64Context::validate_ciphertext)
    /// associated function.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_33() {
        let ciphertext = vec![0x48, 0x49, 0x4a, 0x4b, 0x3d, 0x4d, 0x4e, 0x4f];
        assert_eq![
            Base64Context::validate_ciphertext(&ciphertext), Err(CryptoError::IllegalCharacter(
                "Failure during Base64 ciphertext validation!".to_string(), 4,
                ciphertext,
            ))
        ];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext that contains only one padding byte `=` on
    /// the second last position of the ciphertext **must** fail.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_34() {
        let ciphertext = vec![
            0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
            0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71,
            0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x3d, 0x39,
        ];
        assert_eq![
            Base64Context::validate_ciphertext(&ciphertext), Err(CryptoError::MalformedPadding(
                "Failure during Base64 ciphertext validation!".to_string(),
                ciphertext,
            ))
        ];
    }

    /// Tests the [`validate_ciphertext`](Base64Context::validate_ciphertext) associated function.
    ///
    /// Validating a [base64](Base64Context) ciphertext that contains a character that is not part
    /// of the [base64](Base64Context) alphabet and is on the last position of the ciphertext
    /// **must** fail.
    ///
    /// The padding byte is actually irrelevant for this branch.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_35() {
        let ciphertext = vec![
            0x7a, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
            0x37, 0x38, 0x2b, 0x2f, 0x2f, 0x2b, 0x3d, 0xff,
        ];
        assert_eq![Base64Context::validate_ciphertext(&ciphertext),
                   Err(CryptoError::IllegalCharacter(
                       "Failure during Base64 ciphertext validation!".to_string(), 15,
                       ciphertext,
                   ))];
    }
}