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
// 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 [caesar](CaesarContext) ciphers.

use crate::{
    AtomClass,
    AtomType,
    CaseInsensitiveCiphertext,
    cipher::{
        Cipher,
        Decrypt,
        Encrypt,
        Key,
        shift_byte,
        shift_cipher::remove_non_ascii_letter_bytes,
    },
    CryptoError,
    CryptographicAtom,
    util::text_to_mono_case,
};



/// [`CryptographicAtom`] for handling [Caesar](CaesarContext) plain- and ciphertexts.
///
/// # Usage Example
///
/// ```
/// use encodex::cipher::shift_cipher::CaesarContext;
/// use encodex::cipher::Key;
/// use encodex::cipher::Encrypt;
///
/// // Create new Caesar cipher context.
/// let mut caesar_ctx = CaesarContext::new();
/// // Choose a secure key! KEK!
/// let key = vec![0x46];
/// // Kappa
///
/// let expected_ciphertext = "YMNXNXWJFQQDSTYFXJHZWJHNUMJW".to_string().into_bytes();
/// let plaintext = "This is really not a secure cipher!".to_string().into_bytes();
///
/// assert_eq![caesar_ctx.set_key(&key), Ok(())];
/// assert_eq![caesar_ctx.encrypt(&plaintext), Ok(expected_ciphertext)];
/// ```
///
/// # Plaintext
///
/// A string that consists only of upper- and/or lowercase `ASCII` letters (`0x41`-`0x5a` and
/// `0x61`-`0x7a`) is a valid plaintext for this cipher. All other ciphertexts will be rejected.
///
/// The input for the context instance may contain bytes that are not valid `ASCII` letters. They
/// will be removed before encryption.
///
/// # Ciphertext
///
/// The `Caesar` cipher shifts letters down the alphabet to encode plaintext. That means, that all
/// valid plaintexts are also valid ciphertexts.
///
/// Ciphertexts too may contain non `ASCII` bytes, which will be removed before the decryption
/// process.
///
/// # Key
///
/// The key for this cipher is only one letter. All `26` letters of the `ASCII` alphabet are valid
/// keys for this cipher.
///
/// # Alphabet
///
/// |     ||A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|
/// |-----||-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|
/// |     || | | | | | | | | | | | | | | | | | | | | | | | | | |
/// |**A**||A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|
/// |**B**||B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|
/// |**C**||C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|
/// |**D**||D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|
/// |**E**||E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|
/// |**F**||F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|
/// |**G**||G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|
/// |**H**||H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|
/// |**I**||I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|
/// |**J**||J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|
/// |**K**||K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|
/// |**L**||L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|
/// |**M**||M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|
/// |**N**||N|O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|
/// |**O**||O|P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|
/// |**P**||P|Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|
/// |**Q**||Q|R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|
/// |**R**||R|S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|
/// |**S**||S|T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|
/// |**T**||T|U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|
/// |**U**||U|V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|
/// |**V**||V|W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|
/// |**W**||W|X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|
/// |**X**||X|Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|
/// |**Y**||Y|Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|
/// |**Z**||Z|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|
/// |     || | | | | | | | | | | | | | | | | | | | | | | | | | |
/// |     ||A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|
///
/// # Algorithm
///
/// ## Encode
///
/// To encrypt a message, a letter is chosen and every letter of the plaintext is shifted down the
/// alphabet according to the chosen letter. `A` equals a `0` letters shift, `B` equals a `1` letter
/// shift, `C` equals a `2` letter shift, and so on.
///
/// ## Decode
///
/// Decryption works in the same way. Only the shift direction changes. If the ciphertext has been
/// encrypted by shifting every letter to the right, then, when decrypting, all letters must be
/// shifted to the left.
///
/// On the other hand, one can just shift to the right again, until every letter has been shifted
/// `26` letters in total. This equals a `0` letters shift, because the `ASCII` alphabet consists of
/// `26` letters in total.
///
/// # Security Considerations
///
/// This cipher is not secure at all. Every ciphertext can be broken with in **nanoseconds** because
/// a modern processor can just try out all `26` letters of the `ASCII` alphabet and check which of
/// the resulting plaintexts contains valid words from a language that uses `ASCII` letters.
///
/// Additionally statistical effects of a language are not erased, so a statistical analysis can
/// also easily break this cipher. E.g. when encrypting an english text with the letter `F` (not for
/// respect, but for fail) every `E` will be encrypted to a `J`. That means that the statistical
/// distribution of the letter `J` is the same in the ciphertext as it is for the letter `E` in an
/// english text.
///
/// Although statistical analysis is possible, this is maybe the only cipher where brute force is
/// actually faster than using other analysis methods.
///
/// Besides the fact, that this cipher shouldn't be used anyway, the letter `A` should not be used
/// as key, because, as can be seen in the table above, the latter `A` does not change the
/// plaintext. This equals no protection at all. But since this cipher is so easily breakable, every
/// other letter basically also equals no protection.
pub struct CaesarContext {
    /// The [class](AtomClass) this [`CryptographicAtom`] belongs to.
    atom_class: AtomClass,
    /// The [type](AtomType) of every instance of this [`CryptographicAtom`].
    atom_type: AtomType,
    /// Determines if an instance of `CaesarContext` will use uppercase or lowercase letters.
    ///
    /// This applies to plaintexts, keys and ciphertexts. When this field changes, the key will
    /// also be changed to match its value.
    ///
    /// The default value for every instance is `true`.
    is_uppercase: bool,
    /// The key used by an instance of `CaesarContext`.
    ///
    /// Its initial value is `None`. Keep this value secret at all time for security purposes... oh,
    /// wait...
    key: Option<Vec<u8>>,
}

impl CaesarContext {
    /// Creates a new [`CaesarContext`] [`CryptographicAtom`] with default values.
    pub fn new() -> CaesarContext {
        CaesarContext {
            atom_class: AtomClass::Cipher,
            atom_type: AtomType::Caesar,
            is_uppercase: true,
            key: None,
        }
    }
}

impl CaseInsensitiveCiphertext for CaesarContext {
    /// Returns the capitalization state of a [`CaesarContext`].
    ///
    /// This method always returns a [`Some`] value because [caesar ciphers](CaesarContext) can have
    /// uppercase and lowercase plain- and ciphertexts.
    fn ciphertext_is_capitalized(&self) -> Option<bool> { Some(self.is_uppercase) }

    /// Updates the [capitalization state](CaseInsensitiveCiphertext) of a [`CaesarContext`].
    ///
    /// If the state is changed, the key will be updated to match the new state.
    fn set_ciphertext_capitalization(
        &mut self,
        capitalized: bool,
    ) {
        if self.is_uppercase != capitalized {
            self.is_uppercase = capitalized;
            if let Some(key) = &self.key {
                self.key = Some(text_to_mono_case(key, self.is_uppercase));
            }
        }
    }
}

impl Cipher for CaesarContext {}

impl CryptographicAtom for CaesarContext {
    /// Returns the [class](AtomClass) of a [`CaesarContext`].
    fn get_atom_class(&self) -> AtomClass { self.atom_class }

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

impl Decrypt for CaesarContext {
    /// Decrypts the given ciphertext.
    ///
    /// The ciphertext may contain any non letter `ASCII` bytes and may be uppercase, lowercase or
    /// mixed case. The ciphertext will be cleared of all non letter `ASCII` bytes and then be
    /// decrypted. The returned plaintext will always be uppercase- or lowercase-only, depending on
    /// the setting of the [`CaesarContext`].
    ///
    /// # Errors
    ///
    /// This method will return an error if no key is set when it is called.
    fn decrypt(
        &mut self,
        ciphertext: &Vec<u8>,
    ) -> Result<Vec<u8>, CryptoError> {
        // Save actual key
        let original_key = if let Some(key) = &self.key {
            key[0]
        } else {
            return Err(CryptoError::MissingKey("For Caesar cipher decryption!".to_string()));
        };

        // Calculate the value that is required so that another encryption cancels out the previous
        // encryption and set it on this instance
        let correction = if self.is_uppercase { 0x41 } else { 0x61 };
        let decrypt_key = vec![
            (26 - (original_key - correction)) + correction
        ];
        self.key = Some(decrypt_key);

        // Encrypt again. Unwrap can be called without check, because the only error that can occur
        // is a missing key error and this one has been checked already.
        let plaintext = self.encrypt(ciphertext).unwrap();
        // Restore original key
        self.key = Some(vec![original_key]);
        // Return result
        Ok(plaintext)
    }
}

impl Encrypt for CaesarContext {
    /// Encrypts the given plaintext.
    ///
    /// The plaintext may contain any non letter `ASCII` bytes and may be uppercase, lowercase or
    /// mixed case. The plaintext will be cleared of all non letter `ASCII` bytes and then be
    /// encrypted. The returned ciphertext will always be uppercase- or lowercase-only, depending on
    /// the setting of the [`CaesarContext`].
    ///
    /// # Errors
    ///
    /// This method will return an error if no key is set when it is called.
    fn encrypt(
        &mut self,
        plaintext: &Vec<u8>,
    ) -> Result<Vec<u8>, CryptoError> {
        let cleaned_plaintext = remove_non_ascii_letter_bytes(plaintext);
        let mono_cased_plaintext = text_to_mono_case(
            &cleaned_plaintext, self.is_uppercase,
        );

        let mut ciphertext = Vec::new();
        // The key is already calculated as a value from 0 (A) to 25 (Z), so it already represents
        // the distance for the distance parameter of the shift_byte function.
        let key = if let Some(key) = &self.key {
            key.get(0).unwrap().clone() - if self.is_uppercase { 0x41 } else { 0x61 }
        } else {
            return Err(CryptoError::MissingKey("For Caesar cipher encryption!".to_string()));
        };
        for mut m in mono_cased_plaintext {
            m = m - if self.is_uppercase { 0x41 } else { 0x61 };
            let c = shift_byte(
                m,
                key,
                false,
                // cause 26 letters in the ASCII alphabet
                26,
            );
            ciphertext.push(c + if self.is_uppercase { 0x41 } else { 0x61 });
        }
        Ok(ciphertext)
    }
}

impl Key for CaesarContext {
    /// Returns the currently set key of a [`CaesarContext`] or [`None`] if no key has been
    /// set, yet.
    fn get_key(
        &self
    ) -> Option<&Vec<u8>> {
        if let Some(key) = &self.key {
            Some(key)
        } else {
            None
        }
    }

    /// Sets the key for an instance of `CaesarContext`.
    ///
    /// This method accepts any input. All non `ASCII` letter bytes will be removed from the key and
    /// if it is not empty after this process, the new key will be set in the context.
    ///
    /// The key's bytes will be adjusted to match the current capitalization state of the context.
    /// That means, that if the current capitalization state is only uppercase, the key will be
    /// saved with only uppercase letters, and if the current capitalization state is only lowercase
    /// the key will be saved with only lowercase letters.
    ///
    /// The letters `A` and `a`, although `ASCII` letters, will not be accepted as keys. For an
    /// explanation, see [`CaesarContext`]. If these letters are given as key, the key will not be
    /// updated.
    ///
    /// A key that is too long will be truncated to one byte.
    ///
    /// # Errors
    ///
    /// A [`CryptoError`] is returned if
    ///
    /// * the key was empty (after removing non `ASCII` letter bytes),
    /// * the letter `A` or `a` has been given as a key.
    fn set_key(
        &mut self,
        key: &Vec<u8>,
    ) -> Result<(), CryptoError> {
        let mut clean_key = remove_non_ascii_letter_bytes(key);
        if clean_key.len() > 1 {
            clean_key.truncate(1);
        }
        if clean_key.is_empty() {
            return Err(CryptoError::InvalidKey(
                "For Caesar cipher! Key is empty!".to_string(),
                key.clone(),
            ));
        }
        if clean_key[0] == 0x41 || clean_key[0] == 0x61 {
            return Err(CryptoError::InvalidKey(
                "For Caesar cipher! Illegal character!".to_string(),
                clean_key.clone(),
            ));
        }
        let mono_case_key = text_to_mono_case(
            &clean_key, self.is_uppercase
        );
        self.key = Some(mono_case_key);
        Ok(())
    }
}



/// Test vectors for the [Caesar](CaesarContext) cipher.
#[cfg(any(test, feature = "doc_tests"))]
mod tests {
    use super::*;

    /// Tests the [`get_atom_type`](CaesarContext::get_atom_type) method of the [`CaesarContext`].
    ///
    /// The returned value for [`CaesarContext`] **must** always be [`Caesar`](AtomType::Caesar).
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_01() {
        let ctx = CaesarContext::new();
        assert_eq![ctx.get_atom_type(), AtomType::Caesar];
    }

    /// Tests the [`ciphertext_is_capitalized`](CaesarContext::ciphertext_is_capitalized) method of
    /// the [`CaesarContext`].
    ///
    /// Tests if the capitalization state is `true` as default after creating a new
    /// [`CaesarContext`].
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_02() {
        let ctx = CaesarContext::new();
        assert_eq![ctx.ciphertext_is_capitalized(), Some(true)];
    }

    /// Tests the [`set_ciphertext_capitalization`](CaesarContext::set_ciphertext_capitalization)
    /// method of the [`CaesarContext`].
    ///
    /// Tests if the capitalization state is `false` after setting it to `false`.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_03() {
        let mut ctx = CaesarContext::new();
        ctx.set_ciphertext_capitalization(false);
        assert_eq![ctx.ciphertext_is_capitalized(), Some(false)];
    }

    /// Tests the [`set_ciphertext_capitalization`](CaesarContext::set_ciphertext_capitalization)
    /// method of the [`CaesarContext`].
    ///
    /// Tests if the capitalization state is `true` after setting it to `false` and then to `true`
    /// again.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_04() {
        let mut ctx = CaesarContext::new();
        ctx.set_ciphertext_capitalization(false);
        ctx.set_ciphertext_capitalization(true);
        assert_eq![ctx.ciphertext_is_capitalized(), Some(true)];
    }

    /// Tests the [`set_ciphertext_capitalization`](CaesarContext::set_ciphertext_capitalization)
    /// method of the [`CaesarContext`].
    ///
    /// Tests if the capitalization state is still `true` after setting it to `true`.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_05() {
        let mut ctx = CaesarContext::new();
        ctx.set_ciphertext_capitalization(true);
        assert_eq![ctx.ciphertext_is_capitalized(), Some(true)];
    }

    /// Tests the [`decrypt`](CaesarContext::decrypt) method of the [`CaesarContext`].
    ///
    /// Ciphertext: FYY fhp FYI fbs
    ///
    /// Key: `F`
    ///
    /// Plaintext: ATT ACK ATD AWN
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_06() {
        let ciphertext = vec![
            0x46, 0x59, 0x59,
            0x66, 0x68, 0x70,
            0x46, 0x59, 0x49,
            0x66, 0x62, 0x73,
        ];
        let key = vec![0x46];
        let expected_plaintext = vec![
            0x41, 0x54, 0x54,
            0x41, 0x43, 0x4b,
            0x41, 0x54, 0x44,
            0x41, 0x57, 0x4e,
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Ok(())];

        let plaintext = ctx.decrypt(&ciphertext);
        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Tests the [`decrypt`](CaesarContext::decrypt) method of the [`CaesarContext`].
    ///
    /// Ciphertext: wkh TXL fne URZ qir AMX psv RYH uwk HOD cbg RJ
    ///
    /// Key: `d`
    ///
    /// Plaintext: the qui ckb row nfo xju mps ove rth ela zyd og
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_07() {
        let ciphertext = vec![
            0x77, 0x6b, 0x68,
            0x54, 0x58, 0x4c,
            0x66, 0x6e, 0x65,
            0x55, 0x52, 0x5a,
            0x71, 0x69, 0x72,
            0x41, 0x4d, 0x58,
            0x70, 0x73, 0x76,
            0x52, 0x59, 0x48,
            0x75, 0x77, 0x6b,
            0x48, 0x4f, 0x44,
            0x63, 0x62, 0x67,
            0x52, 0x4a,
        ];
        let key = vec![0x64];
        let expected_plaintext = vec![
            0x74, 0x68, 0x65,
            0x71, 0x75, 0x69,
            0x63, 0x6b, 0x62,
            0x72, 0x6f, 0x77,
            0x6e, 0x66, 0x6f,
            0x78, 0x6a, 0x75,
            0x6d, 0x70, 0x73,
            0x6f, 0x76, 0x65,
            0x72, 0x74, 0x68,
            0x65, 0x6c, 0x61,
            0x7a, 0x79, 0x64,
            0x6f, 0x67,
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Ok(())];
        ctx.set_ciphertext_capitalization(false);

        let plaintext = ctx.decrypt(&ciphertext);
        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Tests the [`decrypt`](CaesarContext::decrypt) method of the [`CaesarContext`].
    ///
    /// Ciphertext: clL yXO
    ///
    /// Key: `X`
    ///
    /// Plaintext: FOO BAR
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_08() {
        let ciphertext = vec![
            0x63, 0x6c, 0x4c,
            0x79, 0x58, 0x4f,
        ];
        let key = vec![0x58];
        let expected_plaintext = vec![
            0x46, 0x4f, 0x4f,
            0x42, 0x41, 0x52,
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Ok(())];

        let plaintext = ctx.decrypt(&ciphertext);
        assert_eq![plaintext, Ok(expected_plaintext)];
    }

    /// Tests the [`decrypt`](CaesarContext::decrypt) method of the [`CaesarContext`].
    ///
    /// If no key has been supplied, a [`CryptoError`] must be returned.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_09() {
        let ciphertext = vec![];
        let mut ctx = CaesarContext::new();
        assert_eq![ctx.decrypt(&ciphertext),
                   Err(CryptoError::MissingKey("For Caesar cipher decryption!".to_string()))];
    }

    /// Tests the [`decrypt`](CaesarContext::decrypt) method of the [`CaesarContext`].
    ///
    /// Because this method is implemented to use the encrypt method, this additional test is
    /// required for the decrypt operation to make sure, that the key is correctly restored after
    /// the decrypt operation.
    ///
    /// It also tests an edge case, namely the empty string.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_10() {
        let ciphertext = vec![];
        let key = vec![0x62];
        let expected_key = vec![0x42];
        let expected_plaintext = vec![];
        let mut ctx = CaesarContext::new();

        assert_eq![ctx.set_key(&key), Ok(())];
        assert_eq![ctx.key, Some(expected_key.clone())];
        assert_eq![ctx.decrypt(&ciphertext), Ok(expected_plaintext)];
        assert_eq![ctx.get_key(), Some(&expected_key)];
    }

    /// Tests the [`encrypt`](CaesarContext::encrypt) method of the [`CaesarContext`].
    ///
    /// Plaintext: ATT ACK ATD AWN
    ///
    /// Key: `F`
    ///
    /// Ciphertext: fyy fhp fyi fbs
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_11() {
        let plaintext = vec![
            0x61, 0x74, 0x74,
            0x61, 0x63, 0x6b,
            0x61, 0x74, 0x64,
            0x61, 0x77, 0x6e,
        ];
        let key = vec![0x46];
        let expected_ciphertext = vec![
            0x66, 0x79, 0x79,
            0x66, 0x68, 0x70,
            0x66, 0x79, 0x69,
            0x66, 0x62, 0x73,
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Ok(())];
        ctx.set_ciphertext_capitalization(false);

        let ciphertext = ctx.encrypt(&plaintext);
        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Tests the [`encrypt`](CaesarContext::encrypt) method of the [`CaesarContext`].
    ///
    /// Plaintext: the qui ckb row nfo xju mps ove rth ela zyd og
    ///
    /// Key: `D`
    ///
    /// Ciphertext: WKH TXL FNE URZ QIR AMX PSV RYH UWK HOD CBG RJ
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_12() {
        let plaintext = vec![
            0x74, 0x68, 0x65,
            0x71, 0x75, 0x69,
            0x63, 0x6b, 0x62,
            0x72, 0x6f, 0x77,
            0x6e, 0x66, 0x6f,
            0x78, 0x6a, 0x75,
            0x6d, 0x70, 0x73,
            0x6f, 0x76, 0x65,
            0x72, 0x74, 0x68,
            0x65, 0x6c, 0x61,
            0x7a, 0x79, 0x64,
            0x6f, 0x67,
        ];
        let key = vec![0x44];
        let expected_ciphertext = vec![
            0x57, 0x4b, 0x48,
            0x54, 0x58, 0x4c,
            0x46, 0x4e, 0x45,
            0x55, 0x52, 0x5a,
            0x51, 0x49, 0x52,
            0x41, 0x4d, 0x58,
            0x50, 0x53, 0x56,
            0x52, 0x59, 0x48,
            0x55, 0x57, 0x4b,
            0x48, 0x4f, 0x44,
            0x43, 0x42, 0x47,
            0x52, 0x4a,
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Ok(())];

        let ciphertext = ctx.encrypt(&plaintext);
        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Tests the [`encrypt`](CaesarContext::encrypt) method of the [`CaesarContext`].
    ///
    /// Plaintext: foo bar
    ///
    /// Key: `X`
    ///
    /// Ciphertext: cll yxo
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_13() {
        let plaintext = vec![
            0x66, 0x6f, 0x6f,
            0x62, 0x61, 0x72,
        ];
        let key = vec![0x58];
        let expected_ciphertext = vec![
            0x63, 0x6c, 0x6c,
            0x79, 0x78, 0x6f,
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Ok(())];
        ctx.set_ciphertext_capitalization(false);

        let ciphertext = ctx.encrypt(&plaintext);
        assert_eq![ciphertext, Ok(expected_ciphertext)];
    }

    /// Tests the [`encrypt`](CaesarContext::encrypt) method of the [`CaesarContext`].
    ///
    /// If no key has been supplied, a [`CryptoError`] must be returned.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_14() {
        let plaintext = vec![];
        let mut ctx = CaesarContext::new();
        assert_eq![ctx.encrypt(&plaintext),
                   Err(CryptoError::MissingKey("For Caesar cipher encryption!".to_string()))];
    }

    /// Tests the [`get_key`](CaesarContext::get_key) method of the [`CaesarContext`].
    ///
    /// The returned value **must** be [`None`] for a newly created [`CaesarContext`].
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_15() {
        let ctx = CaesarContext::new();
        assert_eq![ctx.get_key(), None];
    }

    /// Tests the [`set_key`](CaesarContext::set_key) method of the [`CaesarContext`].
    ///
    /// This test tests the `set_key` method with a valid key.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_16() {
        let key = vec![
            0x46
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Ok(())];

        assert_eq![ctx.get_key(), Some(&key)];
    }

    /// Tests the [`set_key`](CaesarContext::set_key) method of the [`CaesarContext`].
    ///
    /// This test tests the `set_key` method with an invalid key that is too long.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_17() {
        let key = vec![
            0x46, 0x41, 0x41, 0x41,
        ];
        let expected_key = vec![
            0x46
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Ok(())];

        assert_eq![ctx.get_key(), Some(&expected_key)];
    }

    /// Tests the [`set_key`](CaesarContext::set_key) method of the [`CaesarContext`].
    ///
    /// This test tests the `set_key` method with an invalid key that is empty.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_18() {
        let key = vec![];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Err(CryptoError::InvalidKey(
            "For Caesar cipher! Key is empty!".to_string(),
            key,
        ))];

        assert_eq![ctx.get_key(), None];
    }

    /// Tests the [`set_key`](CaesarContext::set_key) method of the [`CaesarContext`].
    ///
    /// This test tests the `set_key` method with an invalid key that contains only bytes outside
    /// the `ASCII` alphabet, which should result in an empty key error.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_19() {
        let key = vec![
            0x40, 0x00, 0xff, 0xcc,
        ];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key), Err(CryptoError::InvalidKey(
            "For Caesar cipher! Key is empty!".to_string(),
            key,
        ))];

        assert_eq![ctx.get_key(), None];
    }

    /// Tests the [`set_key`](CaesarContext::set_key) method of the [`CaesarContext`].
    ///
    /// The letters `A` and `a` do not change the plaintext. They **must not** be accepted as valid
    /// keys.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_20() {
        let key_uppercase_a = vec![0x41];
        let key_lowercase_a = vec![0x61];

        let mut ctx = CaesarContext::new();
        assert_eq![ctx.set_key(&key_uppercase_a), Err(CryptoError::InvalidKey(
            "For Caesar cipher! Illegal character!".to_string(),
            key_uppercase_a,
        ))];
        assert_eq![ctx.get_key(), None];
        assert_eq![ctx.set_key(&key_lowercase_a), Err(CryptoError::InvalidKey(
            "For Caesar cipher! Illegal character!".to_string(),
            key_lowercase_a,
        ))];
        assert_eq![ctx.get_key(), None];
    }

    /// Tests the [`set_key`](CaesarContext::set_key) method of the [`CaesarContext`].
    ///
    /// Lowercase letters must be changed to uppercase if the context is set to uppercase.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_21() {
        let key_lowercase = vec![0x62];
        let key_uppercase = vec![0x42];

        let mut ctx = CaesarContext::new();
        ctx.set_ciphertext_capitalization(true);
        assert_eq![ctx.set_key(&key_lowercase), Ok(())];
        assert_eq![ctx.get_key(), Some(&key_uppercase)];
    }

    /// Tests the [`set_key`](CaesarContext::set_key) method of the [`CaesarContext`].
    ///
    /// Uppercase letters must be changed to lowercase if the context is set to lowercase.
    #[cfg_attr(not(feature = "doc_tests"), test)]
    fn test_22() {
        let key_uppercase = vec![0x42];
        let key_lowercase = vec![0x62];

        let mut ctx = CaesarContext::new();
        ctx.set_ciphertext_capitalization(false);
        assert_eq![ctx.set_key(&key_uppercase), Ok(())];
        assert_eq![ctx.get_key(), Some(&key_lowercase)];
    }

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