include_crypt_crypto/
xor.rs

1use crate::key::EncryptionKey;
2
3/// Default xor key length.
4pub const XOR_KEY_LEN: usize = 32;
5
6/// Encrypts the specified data with the key.
7///
8/// # Parameters
9///
10/// - `data`: The data buffer which can be either encrypted or decrypted. After
11///   this function has been called, it will store the encrypted/decrypted data.
12/// - `key`: The key that should be used to encrypt/decrypt the specified data.
13#[inline(always)]
14pub fn xor<K: AsRef<EncryptionKey>>(data: &mut [u8], key: K) {
15    let key = key.as_ref();
16
17    data.chunks_mut(key.len())
18        .for_each(|d| d.iter_mut().zip(&**key).for_each(|(d, k)| *d ^= *k));
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24
25    #[test]
26    fn test_xor() {
27        let mut data = Vec::from("Hello World".as_bytes());
28        let key = EncryptionKey::new("0xdeadbeef", XOR_KEY_LEN).unwrap();
29
30        xor(data.as_mut_slice(), &key);
31        xor(data.as_mut_slice(), &key);
32
33        assert_eq!(data, b"Hello World");
34    }
35}