x11_input_mirror/
encryption.rs1use chacha;
2use chacha::KeyStream;
3use rand::{thread_rng, Rng};
4use sha3::{Digest, Sha3_256};
5
6pub fn random_fill_25(buf: &mut [u8]) {
7 let mut res = [0u8; 25];
8 thread_rng().fill(&mut res);
9 buf.copy_from_slice(&res);
10}
11
12pub fn is_tampered_16(buf: &[u8]) -> bool {
13 let mut tampered = false;
14 for i in 0..8 {
15 if buf[i] != buf[i + 8] {
16 tampered = true;
17 }
18 }
19 tampered
20}
21
22pub struct ChaCha {
23 internal: Option<chacha::ChaCha>,
24}
25
26impl ChaCha {
27 pub fn new(should_be_encrypted: bool, password: &str, nonce: &[u8; 24]) -> ChaCha {
28 if should_be_encrypted {
29 let secret_key = {
30 let mut hasher = Sha3_256::default();
31 hasher.input(password.as_bytes());
32 let mut result = [0u8; 32];
33 result.copy_from_slice(hasher.result().as_slice());
34 result
35 };
36 ChaCha {
37 internal: Some(chacha::ChaCha::new_xchacha20(&secret_key, nonce)),
38 }
39 } else {
40 ChaCha { internal: None }
41 }
42 }
43 pub fn xor(&mut self, dest: &mut [u8]) {
44 if let Some(ref mut chacha) = self.internal {
45 chacha.xor_read(dest).is_ok();
46 }
47 }
48}