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
pub const BLOCK_SIZE: usize = 1_048_576;
pub const SALT_LEN: usize = 16;
#[derive(Copy, Clone)]
pub enum Algorithm {
Aes256Gcm,
XChaCha20Poly1305,
DeoxysII256,
}
pub static ALGORITHMS: [Algorithm; 3] = [
Algorithm::XChaCha20Poly1305,
Algorithm::Aes256Gcm,
Algorithm::DeoxysII256,
];
impl std::fmt::Display for Algorithm {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Algorithm::Aes256Gcm => write!(f, "AES-256-GCM"),
Algorithm::XChaCha20Poly1305 => write!(f, "XChaCha20-Poly1305"),
Algorithm::DeoxysII256 => write!(f, "Deoxys-II-256"),
}
}
}
#[derive(PartialEq, Eq)]
pub enum Mode {
MemoryMode,
StreamMode,
}
#[must_use]
pub fn gen_nonce(algorithm: &Algorithm, mode: &Mode) -> Vec<u8> {
use rand::{prelude::StdRng, RngCore, SeedableRng};
let mut nonce_len = match algorithm {
Algorithm::Aes256Gcm => 12,
Algorithm::XChaCha20Poly1305 => 24,
Algorithm::DeoxysII256 => 15,
};
if mode == &Mode::StreamMode {
nonce_len -= 4;
}
let mut nonce = vec![0u8; nonce_len];
StdRng::from_entropy().fill_bytes(&mut nonce);
nonce
}