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
use crate::common::alphabet;
use crate::common::alphabet::Alphabet;
use crate::common::cipher::Cipher;
use crate::common::keygen::cyclic_keystream;
use crate::common::substitute;
pub struct Vigenere {
key: String,
}
impl Cipher for Vigenere {
type Key = String;
type Algorithm = Vigenere;
fn new(key: String) -> Vigenere {
if key.is_empty() {
panic!("The key is empty.");
}
if !alphabet::STANDARD.is_valid(&key) {
panic!("The key contains a non-alphabetic symbol.");
}
Vigenere { key }
}
fn encrypt(&self, message: &str) -> Result<String, &'static str> {
Ok(substitute::key_substitution(
message,
&cyclic_keystream(&self.key, message),
|mi, ki| alphabet::STANDARD.modulo((mi + ki) as isize),
))
}
fn decrypt(&self, ciphertext: &str) -> Result<String, &'static str> {
Ok(substitute::key_substitution(
ciphertext,
&cyclic_keystream(&self.key, ciphertext),
|ci, ki| alphabet::STANDARD.modulo(ci as isize - ki as isize),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encrypt_test() {
let message = "attackatdawn";
let v = Vigenere::new(String::from("lemon"));
assert_eq!("lxfopvefrnhr", v.encrypt(message).unwrap());
}
#[test]
fn decrypt_test() {
let ciphertext = "lxfopvefrnhr";
let v = Vigenere::new(String::from("lemon"));
assert_eq!("attackatdawn", v.decrypt(ciphertext).unwrap());
}
#[test]
fn mixed_case() {
let message = "Attack at Dawn!";
let v = Vigenere::new(String::from("giovan"));
let ciphertext = v.encrypt(message).unwrap();
let plain_text = v.decrypt(&ciphertext).unwrap();
assert_eq!(plain_text, message);
}
#[test]
fn with_utf8() {
let v = Vigenere::new(String::from("utfeightisfun"));
let message = "Peace 🗡️ Freedom and Liberty!";
let encrypted = v.encrypt(message).unwrap();
let decrypted = v.decrypt(&encrypted).unwrap();
assert_eq!(decrypted, message);
}
#[test]
fn valid_key() {
Vigenere::new(String::from("LeMon"));
}
#[test]
#[should_panic]
fn key_with_symbols() {
Vigenere::new(String::from("!em@n"));
}
#[test]
#[should_panic]
fn key_with_whitespace() {
Vigenere::new(String::from("wow this key is a real lemon"));
}
}