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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#![allow(clippy::match_same_arms)]
#[cfg(feature = "aes")]
use aes::Aes256;
#[cfg(feature = "aes-ctr")]
use aes_ctr::Aes256Ctr;
#[allow(unused_imports)]
use block_modes::block_padding::Pkcs7;
#[allow(unused_imports)]
use block_modes::{BlockMode, Cbc};
#[cfg(feature = "chacha20")]
use chacha20::ChaCha20;
use rand::prelude::*;
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[allow(unused_imports)]
use std::cmp;
#[allow(unused_imports)]
use stream_cipher::generic_array::GenericArray;
#[allow(unused_imports)]
use stream_cipher::{NewStreamCipher, SyncStreamCipher};
use thiserror::Error;
#[allow(unused_imports)]
use zeroize::Zeroize;
use crate::repository::Key;
#[derive(Error, Debug)]
pub enum EncryptionError {
#[error("Invalid key/IV length used to construct encryptor/decryptor")]
InvalidKeyIVLength(#[from] block_modes::InvalidKeyIvLength),
#[error("Error with block mode encryption/decryption")]
BlockModeError(#[from] block_modes::BlockModeError),
}
type Result<T> = std::result::Result<T, EncryptionError>;
#[derive(Copy, Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash)]
pub enum Encryption {
NoEncryption,
AES256CBC { iv: [u8; 16] },
AES256CTR { iv: [u8; 16] },
ChaCha20 { iv: [u8; 12] },
}
impl Encryption {
pub fn new_aes256cbc() -> Encryption {
let mut iv: [u8; 16] = [0; 16];
thread_rng().fill_bytes(&mut iv);
Encryption::AES256CBC { iv }
}
pub fn new_aes256ctr() -> Encryption {
let mut iv: [u8; 16] = [0; 16];
thread_rng().fill_bytes(&mut iv);
Encryption::AES256CTR { iv }
}
pub fn new_chacha20() -> Encryption {
let mut iv: [u8; 12] = [0; 12];
thread_rng().fill_bytes(&mut iv);
Encryption::ChaCha20 { iv }
}
pub fn key_length(&self) -> usize {
match self {
Encryption::NoEncryption => 16,
Encryption::AES256CBC { .. } => 32,
Encryption::AES256CTR { .. } => 32,
Encryption::ChaCha20 { .. } => 32,
}
}
pub fn encrypt(&mut self, data: &[u8], key: &Key) -> Vec<u8> {
self.encrypt_bytes(data, key.key())
}
#[allow(unused_variables)]
pub fn encrypt_bytes(&mut self, data: &[u8], key: &[u8]) -> Vec<u8> {
*self = self.new_iv();
match self {
Encryption::NoEncryption => data.to_vec(),
Encryption::AES256CBC { iv } => {
cfg_if::cfg_if! {
if #[cfg(feature = "aes")] {
let mut proper_key: [u8; 32] = [0; 32];
proper_key[..cmp::min(key.len(), 32)]
.clone_from_slice(&key[..cmp::min(key.len(), 32)]);
let encryptor: Cbc<Aes256, Pkcs7> =
Cbc::new_var(&proper_key, &iv[..])
.expect("Unable to encrypt data. Something is *seriously* wrong. Please contact a maintainer.");
let final_result = encryptor.encrypt_vec(data);
proper_key.zeroize();
final_result
} else {
unimplemented!("Asuran has not been compiled with AES support.")
}
}
}
Encryption::AES256CTR { iv } => {
cfg_if::cfg_if! {
if #[cfg(feature = "aes-ctr")] {
let mut proper_key: [u8; 32] = [0; 32];
proper_key[..cmp::min(key.len(), 32)]
.clone_from_slice(&key[..cmp::min(key.len(), 32)]);
let key = GenericArray::from_slice(&key);
let iv = GenericArray::from_slice(&iv[..]);
let mut encryptor = Aes256Ctr::new(&key, &iv);
let mut final_result = data.to_vec();
encryptor.apply_keystream(&mut final_result);
proper_key.zeroize();
final_result
} else {
unimplemented!("Asuran has not been compiled with AES-CTR Support")
}
}
}
Encryption::ChaCha20 { iv } => {
cfg_if::cfg_if! {
if #[cfg(feature = "chacha20")] {
let mut proper_key: [u8; 32] = [0; 32];
proper_key[..cmp::min(key.len(), 32)]
.clone_from_slice(&key[..cmp::min(key.len(), 32)]);
let key = GenericArray::from_slice(&key);
let iv = GenericArray::from_slice(&iv[..]);
let mut encryptor = ChaCha20::new(&key, &iv);
let mut final_result = data.to_vec();
encryptor.apply_keystream(&mut final_result);
proper_key.zeroize();
final_result
} else {
unimplemented!("Asuran has not been compiled with ChaCha20 support")
}
}
}
}
}
pub fn decrypt(&self, data: &[u8], key: &Key) -> Result<Vec<u8>> {
self.decrypt_bytes(data, key.key())
}
#[allow(unused_variables)]
pub fn decrypt_bytes(&self, data: &[u8], key: &[u8]) -> Result<Vec<u8>> {
match self {
Encryption::NoEncryption => Ok(data.to_vec()),
Encryption::AES256CBC { iv } => {
cfg_if::cfg_if! {
if #[cfg(feature = "aes")] {
let mut proper_key: [u8; 32] = [0; 32];
proper_key[..cmp::min(key.len(), 32)]
.clone_from_slice(&key[..cmp::min(key.len(), 32)]);
let decryptor: Cbc<Aes256, Pkcs7> = Cbc::new_var(&key, &iv[..])?;
let final_result = decryptor.decrypt_vec(data)?;
proper_key.zeroize();
Ok(final_result)
} else {
unimplemented!("Asuran has not been compiled with AES support")
}
}
}
Encryption::AES256CTR { iv } => {
cfg_if::cfg_if! {
if #[cfg(feature = "aes-ctr")] {
let mut proper_key: [u8; 32] = [0; 32];
proper_key[..cmp::min(key.len(), 32)]
.clone_from_slice(&key[..cmp::min(key.len(), 32)]);
let key = GenericArray::from_slice(&key);
let iv = GenericArray::from_slice(&iv[..]);
let mut decryptor = Aes256Ctr::new(&key, &iv);
let mut final_result = data.to_vec();
decryptor.apply_keystream(&mut final_result);
proper_key.zeroize();
Ok(final_result)
} else {
unimplemented!("Asuran has not been compiled with AES support")
}
}
}
Encryption::ChaCha20 { iv } => {
cfg_if::cfg_if! {
if #[cfg(feature = "chacha20")] {
let mut proper_key: [u8; 32] = [0; 32];
proper_key[..cmp::min(key.len(), 32)]
.clone_from_slice(&key[..cmp::min(key.len(), 32)]);
let key = GenericArray::from_slice(&key);
let iv = GenericArray::from_slice(&iv[..]);
let mut decryptor = ChaCha20::new(&key, &iv);
let mut final_result = data.to_vec();
decryptor.apply_keystream(&mut final_result);
proper_key.zeroize();
Ok(final_result)
} else {
unimplemented!("Asuran has not been compiled with ChaCha20 support")
}
}
}
}
}
pub fn new_iv(self) -> Encryption {
match self {
Encryption::NoEncryption => Encryption::NoEncryption,
Encryption::AES256CBC { .. } => Encryption::new_aes256cbc(),
Encryption::AES256CTR { .. } => Encryption::new_aes256ctr(),
Encryption::ChaCha20 { .. } => Encryption::new_chacha20(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str;
fn test_encryption(mut enc: Encryption) {
let mut key: [u8; 32] = [0; 32];
thread_rng().fill_bytes(&mut key);
let data_string =
"The quick brown fox jumps over the lazy dog. Jackdaws love my big sphinx of quartz.";
let encrypted_string = enc.encrypt_bytes(data_string.as_bytes(), &key);
let decrypted_bytes = enc.decrypt_bytes(&encrypted_string, &key).unwrap();
let decrypted_string = str::from_utf8(&decrypted_bytes).unwrap();
println!("Input string: {}", data_string);
println!("Input bytes: \n{:X?}", data_string.as_bytes());
println!("Encrypted bytes: \n{:X?}", encrypted_string);
println!("Decrypted bytes: \n{:X?}", decrypted_bytes);
println!("Decrypted string: {}", decrypted_string);
assert_eq!(data_string, decrypted_string);
}
#[test]
fn test_aes256cbc() {
let enc = Encryption::new_aes256cbc();
test_encryption(enc);
}
#[test]
fn test_aes256ctr() {
let enc = Encryption::new_aes256ctr();
test_encryption(enc);
}
}