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
//! The ADFGVX cipher was a field cipher used by the German Army on the Western Front during World War I.
//!
//! ADFGVX was an extension of an earlier cipher called ADFGX. It uses a polybius square and a
//! columnar transposition cipher.
//!
use columnar_transposition::ColumnarTransposition;
use common::cipher::Cipher;
use common::{alphabet, keygen};
use std::string::String;
use Polybius;

const ADFGVX_CHARS: [char; 6] = ['A', 'D', 'F', 'G', 'V', 'X'];

/// This struct is created by the `new()` method. See its documentation for more.
pub struct ADFGVX {
    polybius_cipher: Polybius,
    columnar_cipher: ColumnarTransposition,
}

impl Cipher for ADFGVX {
    type Key = (String, String, Option<char>);
    type Algorithm = ADFGVX;

    /// Initialise a ADFGVX cipher.
    ///
    /// The `key` tuple maps to the following `(String, String, Option<char>) = (polybius_key,
    /// columnar_key, null_char)`. Where ...
    ///
    /// * The `polybius_key` is used to init a polybius cipher. See it's documentation for more
    /// information.
    /// * The `columnar_key` is used to init a columnar transposition cipher. See it's
    /// documentation for more information.
    /// * The `null_char` is an optional character that will be used to pad uneven messages
    /// during the columnar transposition stage. See the `columnar_transposition` documentation
    /// for more information.
    ///
    /// # Panics
    /// * (see the documentation for Polybius and ColumnarTransposition)
    ///
    fn new(key: (String, String, Option<char>)) -> ADFGVX {
        // Generate the keyed alphabet key for the polybius square
        let p_key = keygen::keyed_alphabet(&key.0, &alphabet::ALPHANUMERIC, false);

        ADFGVX {
            polybius_cipher: Polybius::new((p_key, ADFGVX_CHARS, ADFGVX_CHARS)),
            columnar_cipher: ColumnarTransposition::new((key.1, key.2)),
        }
    }

    /// Encrypt a message using a ADFGVX cipher.
    ///
    /// # Examples
    /// Basic usage:
    ///
    /// ```
    /// use cipher_crypt::{Cipher, ADFGVX};
    ///
    /// let polybius_key = String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8");
    /// let columnar_key = String::from("GERMAN");
    /// let null_char = None;
    ///
    /// let a = ADFGVX::new((
    ///     polybius_key,
    ///     columnar_key,
    ///     null_char
    /// ));
    ///
    /// let cipher_text = concat!(
    ///     "gfxffgxgDFAXDAVGDgxvadaaxxXFDDFGGGFdfaxdavgdVDAGFAXVVxfdd",
    ///     "fgggfVVVAGFFAvvvagffaGXVADAAXXvdagfaxvvGFXFFGXG"
    /// );
    ///
    /// assert_eq!(
    ///     cipher_text,
    ///     a.encrypt("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    ///         .unwrap()
    /// );
    /// ```
    ///
    fn encrypt(&self, message: &str) -> Result<String, &'static str> {
        //Step 1: encrypt using polybius
        let step_one = self.polybius_cipher.encrypt(message)?;
        //Step 2: encrypt with columnar and return
        self.columnar_cipher.encrypt(&step_one)
    }

    /// Decrypt a message using a ADFGVX cipher.
    ///
    /// # Examples
    /// Basic usage:
    ///
    /// ```
    /// use cipher_crypt::{Cipher, ADFGVX};
    ///
    /// let polybius_key = String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8");
    /// let columnar_key = String::from("GERMAN");
    /// let null_char = None;
    ///
    /// let a = ADFGVX::new((
    ///     polybius_key,
    ///     columnar_key,
    ///     null_char
    /// ));
    ///
    /// let cipher_text = concat!(
    ///     "gfxffgxgDFAXDAVGD gxvadaaxxXFDDFGGGFdfaxdav",
    ///     "gdVDAGFAXVVxfddfgggfVVVAGFFA vvvagffaGXVADAAXX vdagfaxvvGFXFFGXG "
    /// );
    ///
    /// assert_eq!(
    ///     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
    ///      a.decrypt(cipher_text).unwrap()
    /// );
    /// ```
    ///
    fn decrypt(&self, ciphertext: &str) -> Result<String, &'static str> {
        //Step 1: decrypt using columnar
        let step_one = self.columnar_cipher.decrypt(ciphertext)?;
        //Step 2: decrypt using polybius
        self.polybius_cipher.decrypt(&step_one)
    }
}

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

    #[test]
    fn encrypt_simple() {
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("GERMAN"),
            None,
        ));

        let cipher_text = concat!(
            "gfxffgxgDFAXDAVGDgxvadaaxxXFDDFGGGFdfaxdavgdVDAGFAX",
            "VVxfddfgggfVVVAGFFAvvvagffaGXVADAAXXvdagfaxvvGFXFFGXG"
        );
        assert_eq!(
            cipher_text,
            a.encrypt("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
                .unwrap()
        );
    }

    #[test]
    fn encrypt_with_space_padding() {
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("GERMAN"),
            Some(' '),
        ));

        // Note: this works as per crate version 0.11.0 - and leaves a trailing
        //       ' ' in the ciphertext.
        let cipher_text = concat!(
            "gfxffgxgDFAXDAVGD gxvadaaxxXFDDFGGGFdfaxdavgdVDAGFAX",
            "VVxfddfgggfVVVAGFFA vvvagffaGXVADAAXX vdagfaxvvGFXFFGXG "
        );
        assert_eq!(
            cipher_text,
            a.encrypt("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
                .unwrap()
        );
    }

    #[test]
    fn decrypt_message() {
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("GERMAN"),
            None,
        ));

        let cipher_text = concat!(
            "gfxffgxgDFAXDAVGDgxvadaaxxXFDDFGGGFdfaxdavgdVDAGFAX",
            "VVxfddfgggfVVVAGFFAvvvagffaGXVADAAXXvdagfaxvvGFXFFGXG"
        );
        assert_eq!(
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
            a.decrypt(cipher_text).unwrap()
        );
    }

    #[test]
    fn decrypt_with_space_padding() {
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("GERMAN"),
            Some(' '),
        ));

        // Note: this works as per crate version 0.11.0 - and leaves a trailing
        //       ' ' in the ciphertext.
        let cipher_text = concat!(
            "gfxffgxgDFAXDAVGD gxvadaaxxXFDDFGGGFdfaxdavgdVDAGFAX",
            "VVxfddfgggfVVVAGFFA vvvagffaGXVADAAXX vdagfaxvvGFXFFGXG "
        );
        assert_eq!(
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
            a.decrypt(cipher_text).unwrap()
        );
    }

    #[test]
    fn simple() {
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("VICTORY"),
            None,
        ));

        let plain_text = concat!(
            "We attack at dawn, not later when it is light, ",
            "or at some strange time of the clock. Only at dawn."
        );
        assert_eq!(
            a.decrypt(&a.encrypt(plain_text).unwrap()).unwrap(),
            plain_text
        );
    }

    #[test]
    fn simple_with_padding() {
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("VICTORY"),
            Some('\u{0}'),
        ));

        let plain_text = concat!(
            "We attack at dawn, not later when it is light, ",
            "or at some strange time of the clock. Only at dawn."
        );
        assert_eq!(
            a.decrypt(&a.encrypt(plain_text).unwrap()).unwrap(),
            plain_text
        );
    }

    #[test]
    fn plaintext_with_padding() {
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("VICTORY"),
            Some(' '),
        ));

        let plain_text = "This will fail because of spaces.";
        assert!(a.encrypt(plain_text).is_err());
    }

    #[test]
    fn with_utf8() {
        let plain_text = "Attack 🗡️ the east wall";
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("GERMAN"),
            None,
        ));

        assert_eq!(
            plain_text,
            a.decrypt(&a.encrypt(plain_text).unwrap()).unwrap()
        );
    }

    #[test]
    fn with_utf8_with_padding() {
        let plain_text = "Attack 🗡️ the east wall";
        let a = ADFGVX::new((
            String::from("ph0qg64mea1yl2nofdxkr3cvs5zw7bj9uti8"),
            String::from("GERMAN"),
            Some('\u{0}'),
        ));

        assert_eq!(
            plain_text,
            a.decrypt(&a.encrypt(plain_text).unwrap()).unwrap()
        );
    }

    #[test]
    #[should_panic]
    fn invalid_key_phrase() {
        ADFGVX::new((String::from("F@il"), String::from("GERMAN"), None));
    }

}