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
const ROUNDS: u64 = 32;
macro_rules! round {
($x:ident, $y:ident, $k:ident) => {
$x = $x.rotate_right(8);
$x = $x.wrapping_add($y);
$x ^= $k;
$y = $y.rotate_left(3);
$y ^= $x;
}
}
macro_rules! inv_round {
($x:ident, $y:ident, $k:ident) => {
$y ^= $x;
$y = $y.rotate_right(3);
$x ^= $k;
$x = $x.wrapping_sub($y);
$x = $x.rotate_left(8);
}
}
pub fn encrypt_block((mut m1, mut m2): (u64, u64), (mut k1, mut k2): (u64, u64)) -> (u64, u64) {
round!(m1, m2, k2);
for i in 0..ROUNDS - 1 {
round!(k1, k2, i);
round!(m1, m2, k2);
}
(m1, m2)
}
pub struct Key {
schedule: [u64; ROUNDS as usize],
}
impl Key {
pub fn new(mut k1: u64, mut k2: u64) -> Key {
let mut ret = Key {
schedule: [0; ROUNDS as usize],
};
for i in 0..ROUNDS {
ret.schedule[i as usize] = k2;
round!(k1, k2, i);
}
ret
}
pub fn encrypt_block(&self, (mut m1, mut m2): (u64, u64)) -> (u64, u64) {
for &k in &self.schedule {
round!(m1, m2, k);
}
(m1, m2)
}
pub fn decrypt_block(&self, (mut c1, mut c2): (u64, u64)) -> (u64, u64) {
for &k in self.schedule.iter().rev() {
inv_round!(c1, c2, k);
}
(c1, c2)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encrypt_decrypt() {
let mut a = 394u64;
let mut b = 320948u64;
let mut x;
let mut y = 234087328470234u64;
for _ in 0..9000 {
a = a.wrapping_mul(206066389);
b ^= a;
x = y.wrapping_add(a);
y = x.wrapping_mul(b | 1);
let key = Key::new(x, y);
assert_eq!(key.decrypt_block(key.encrypt_block((a, b))), (a, b));
assert_eq!(key.encrypt_block((a, b)), encrypt_block((a, b), (x, y)));
}
}
#[test]
fn test_vectors() {
assert_eq!(encrypt_block((0x6c61766975716520, 0x7469206564616d20), (0x0f0e0d0c0b0a0908, 0x0706050403020100)), (0xa65d985179783265, 0x7860fedf5c570d18));
}
}