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
//! The Columnar cipher is a transposition cipher. In columnar transposition the message is
//! written out in rows of a fixed length, and then transcribed to a message via the columns.
//! The columns are scrambled based on a secret key.
//!
//! Columnar transposition continued to be used as a component of more complex ciphers up
//! until the 1950s.
//!
use common::cipher::Cipher;
use common::{keygen, alphabet};
use common::alphabet::Alphabet;

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

impl Cipher for ColumnarTransposition {
    type Key = String;
    type Algorithm = ColumnarTransposition;

    /// Initialize a Columnar Transposition cipher given a specific key.
    ///
    /// Will return `Err` if one of the following conditions is detected:
    ///
    /// * The `key` length is 0.
    /// * The `key` contains non-alphanumeric symbols.
    /// * The `key` contains duplicate characters.
    fn new(key: String) -> Result<ColumnarTransposition, &'static str> {
        keygen::columnar_key(&key)?;
        Ok(ColumnarTransposition { key: key })
    }

    /// Encrypt a message with a Columnar Transposition cipher.
    ///
    /// Whilst all characters (including utf8) can be encrypted during the transposition process,
    /// it is important to note that the space character is also treated as padding. As such,
    /// whitespace characters at the end of a message are not preserved during the decryption
    /// process.
    ///
    /// # Examples
    /// Basic usage:
    ///
    /// ```
    /// use cipher_crypt::{Cipher, ColumnarTransposition};
    ///
    /// let ct = ColumnarTransposition::new(String::from("zebras")).unwrap();
    /// assert_eq!("res pce!uemeers -ta Ss g", ct.encrypt("Super-secret message!").unwrap());
    /// ```
    fn encrypt(&self, message: &str) -> Result<String, &'static str> {
        let mut key = keygen::columnar_key(&self.key)?;

        //Construct the column
        let mut i = 0;
        let mut chars = message.chars();
        loop {
            if let Some(c) = chars.next() {
                key[i].1.push(c);
            } else if i > 0 {
                key[i].1.push(' '); //We must add padding characters
            } else {
                break;
            }

            i = (i + 1) % key.len();
        }

        //Sort the key based on it's alphabet positions
        key.sort_by(|a, b|
            alphabet::STANDARD.find_position(a.0).unwrap()
            .cmp(&alphabet::STANDARD.find_position(b.0).unwrap())
        );

        //Construct the cipher text
        let mut ciphertext = String::new();
        for column in key.iter() {
            for chr in column.1.iter() {
                ciphertext.push(*chr);
            }
        }

        Ok(ciphertext)
    }

    /// Decrypt a ciphertext with a Columnar Transposition cipher.
    ///
    /// # Examples
    /// Basic usage:
    ///
    /// ```
    /// use cipher_crypt::{Cipher, ColumnarTransposition};
    ///
    /// let ct = ColumnarTransposition::new(String::from("zebras")).unwrap();
    /// assert_eq!("Super-secret message!", ct.decrypt("res pce!uemeers -ta Ss g").unwrap());
    /// ```
    fn decrypt(&self, ciphertext: &str) -> Result<String, &'static str> {
        let mut key = keygen::columnar_key(&self.key)?;

        //Sort the key so that it's in its encryption order
        key.sort_by(|a, b|
            alphabet::STANDARD.find_position(a.0).unwrap()
            .cmp(&alphabet::STANDARD.find_position(b.0).unwrap())
        );

        //Transcribe the ciphertext along each column
        let mut chars = ciphertext.chars();
        let col_size: usize = (ciphertext.chars().count() as f32 / self.key.len() as f32).ceil() as usize;

        'outer: for column in &mut key {
            loop {
                if column.1.len() >= col_size {
                    break;
                } else if let Some(c) = chars.next() {
                    column.1.push(c);
                } else {
                    break 'outer; //No more characters left in ciphertext
                }
            }
        }

        let mut plaintext = String::new();
        for i in 0..col_size {
            for chr in self.key.chars(){
                if let Some(column) = key.iter().find(|x| x.0 == chr){
                    plaintext.push(column.1[i]);
                } else {
                    return Err("Could not find column during decryption.");
                }
            }
        }

        Ok(plaintext.trim_right().to_string())
    }
}

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

    #[test]
    fn simple(){
        let message = "wearediscovered";
        let ct = ColumnarTransposition::new(String::from("zebras")).unwrap();

        assert_eq!(ct.decrypt(&ct.encrypt(message).unwrap()).unwrap(), message);
    }

    #[test]
    fn with_utf8(){
        let c = ColumnarTransposition::new(String::from("zebras")).unwrap();
        let message = "Peace, Freedom 🗡️ and Liberty!";
        let encrypted = c.encrypt(message).unwrap();
        assert_eq!(c.decrypt(&encrypted).unwrap(), message);
    }

    #[test]
    fn single_column(){
        let message = "we are discovered";
        let ct = ColumnarTransposition::new(String::from("z")).unwrap();
        assert_eq!(ct.decrypt(&ct.encrypt(message).unwrap()).unwrap(), message);
    }

    #[test]
    fn trailing_spaces(){
        let message = "we are discovered  "; //The trailing spaces will be stripped
        let ct = ColumnarTransposition::new(String::from("z")).unwrap();

        assert_eq!(ct.decrypt(&ct.encrypt(message).unwrap()).unwrap(), "we are discovered");
    }
}