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
use num::integer::gcd;
use common::{alphabet, substitute};
use common::alphabet::Alphabet;
use common::cipher::Cipher;
pub struct Affine {
a_b: (usize, usize),
}
impl Cipher for Affine {
type Key = (usize, usize);
type Algorithm = Affine;
fn new(a_b: (usize, usize)) -> Result<Affine, &'static str> {
if a_b.0 < 1 || a_b.1 < 1 {
return Err("The keys a & b must be >= 1.");
}
if a_b.0 > 26 || a_b.1 > 26 {
return Err("The keys a & b must be <= 26.");
}
if gcd(a_b.0, 26) > 1 {
return Err("The key 'a' cannot share a common factor with 26.");
}
Ok(Affine { a_b: a_b })
}
fn encrypt(&self, message: &str) -> Result<String, &'static str> {
substitute::shift_substitution(message, |idx| {
alphabet::STANDARD.modulo(((self.a_b.0 * idx) + self.a_b.1) as isize)
})
}
fn decrypt(&self, ciphertext: &str) -> Result<String, &'static str> {
let a_inv = alphabet::STANDARD
.multiplicative_inverse(self.a_b.0 as isize)
.expect("Multiplicative inverse for 'a' could not be calculated.");
substitute::shift_substitution(ciphertext, |idx| {
alphabet::STANDARD.modulo(a_inv as isize * (idx as isize - self.a_b.1 as isize))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encrypt_message() {
let a = Affine::new((3, 7)).unwrap();
assert_eq!("Hmmhnl hm qhvu!", a.encrypt("Attack at dawn!").unwrap());
}
#[test]
fn decrypt_message() {
let a = Affine::new((3, 7)).unwrap();
assert_eq!("Attack at dawn!", a.decrypt("Hmmhnl hm qhvu!").unwrap());
}
#[test]
fn with_utf8() {
let a = Affine::new((15, 10)).unwrap();
let message = "Peace ✌️ Freedom and Liberty!";
assert_eq!(message, a.decrypt(&a.encrypt(message).unwrap()).unwrap());
}
#[test]
fn exhaustive_encrypt() {
let message = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for a in 1..27 {
if gcd(a, 26) > 1 {
continue;
}
for b in 1..27 {
let a = Affine::new((a, b)).unwrap();
assert_eq!(message, a.decrypt(&a.encrypt(message).unwrap()).unwrap());
}
}
}
#[test]
fn valid_key() {
assert!(Affine::new((15, 17)).is_ok());
}
#[test]
fn b_shares_factor() {
assert!(Affine::new((15, 2)).is_ok());
}
#[test]
fn a_shares_factor() {
assert!(Affine::new((2, 15)).is_err());
}
#[test]
fn keys_to_small() {
assert!(Affine::new((0, 10)).is_err());
}
#[test]
fn keys_to_big() {
assert!(Affine::new((30, 51)).is_err());
}
}