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
//! The Caesar cipher is named after Julius Caesar, who used it (allegedy) with a shift of three
//!to protect messages of military significance.
//!
//! As with all single-alphabet substitution ciphers, the Caesar cipher is easily broken
//!and in modern practice offers essentially no communication security.
//!
use common::alphabet;

/// A Caesar cipher.
///
/// This struct is created by the `new()` method. See its documentation for more.
pub struct Caesar {
    shift: usize,
}

impl Caesar {
    /// Initialise a Caesar cipher given a specific shift value.
    ///
    /// Will return `Err` if the shift value is outside the range `1-26`.
    pub fn new(shift: usize) -> Result<Caesar, &'static str> {
        if shift >= 1 && shift <= 26 {
            return Ok(Caesar {shift: shift});
        }

        Err("Invalid shift factor. Must be in the range 1-26")
    }

    /// Encrypt a message using a Caesar cipher.
    ///
    /// # Examples
    /// Basic usage:
    ///
    /// ```
    /// use cipher_crypt::caesar::Caesar;
    ///
    /// let caesar = Caesar::new(3).unwrap();
    /// assert_eq!("Dwwdfn dw gdzq!", caesar.encrypt("Attack at dawn!"));
    /// ```
    pub fn encrypt(&self, message: &str) -> String {
        // Encryption of a letter:
        //         E(x) = (x + n) mod 26
        // Where;  x = position of letter in alphabet
        //         n = shift factor (or key)
        alphabet::mono_substitute(message, |idx| (idx + self.shift) % 26)
    }

    /// Decrypt a message using a Caesar cipher.
    ///
    /// # Examples
    /// Basic usage:
    ///
    /// ```
    /// use cipher_crypt::caesar::Caesar;
    ///
    /// let caesar = Caesar::new(3).unwrap();
    /// assert_eq!("Attack at dawn!", caesar.decrypt("Dwwdfn dw gdzq!"));
    /// ```
    pub fn decrypt(&self, cipher_text: &str) -> String {
        // Decryption of a letter:
        //         D(x) = (x - n) mod 26
        // Where;  x = position of letter in alphabet
        //         n = shift factor (or key)
        let decrypt = |idx| {
            let a: isize = idx as isize - self.shift as isize;
            (((a % 26) + 26) % 26) as usize
            //Rust does not natievly support negative wrap around modulo operations
        };

        alphabet::mono_substitute(cipher_text, decrypt)
    }
}

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

    #[test]
    fn encrypt_message() {
        let c = Caesar::new(2).unwrap();
        assert_eq!("Cvvcem cv fcyp!", c.encrypt("Attack at dawn!"));
    }

    #[test]
    fn decrypt_message() {
        let c = Caesar::new(2).unwrap();
        assert_eq!("Attack at dawn!", c.decrypt("Cvvcem cv fcyp!"));
    }

    #[test]
    fn with_emoji(){
        let c = Caesar::new(3).unwrap();
        let message = "Peace, Freedom and Liberty! 🗡️";
        let encrypted = c.encrypt(message);
        let decrypted = c.decrypt(&encrypted);

        assert_eq!(decrypted, message);
    }

    #[test]
    fn exhaustive_encrypt(){
        //Test with every possible shift combination
        let message = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for i in 1..26 {
            let c = Caesar::new(i).unwrap();
            let encrypted = c.encrypt(message);
            let decrypted = c.decrypt(&encrypted);
            assert_eq!(decrypted, message);
        }
    }

    #[test]
    fn key_to_small() {
        assert!(Caesar::new(0).is_err());
    }

    #[test]
    fn key_to_big() {
        assert!(Caesar::new(27).is_err());
    }
}