xor_cipher/
lib.rs

1//! Simple, reusable and optimized XOR ciphers in Rust.
2
3#![forbid(unsafe_code)]
4#![deny(missing_docs)]
5#![cfg_attr(not(feature = "std"), no_std)]
6
7/// Applies XOR operation (`byte ^ key`) for each `byte` in `data`.
8///
9/// This function is its own inverse.
10#[inline]
11pub fn xor<D: AsMut<[u8]>>(mut data: D, key: u8) {
12    fn xor_inner(data: &mut [u8], key: u8) {
13        data.iter_mut().for_each(|byte| *byte ^= key);
14    }
15
16    xor_inner(data.as_mut(), key);
17}
18
19/// Applies XOR operation (`byte ^ key_byte`) for each `byte` in `data`
20/// and `key_byte` in `key`, which is cycled to fit the length of the `data`.
21///
22/// This function is its own inverse.
23#[inline]
24pub fn cyclic_xor<D: AsMut<[u8]>, K: AsRef<[u8]>>(mut data: D, key: K) {
25    fn cyclic_xor_inner(data: &mut [u8], key: &[u8]) {
26        data.iter_mut()
27            .zip(key.iter().cycle())
28            .for_each(|(byte, key_byte)| *byte ^= key_byte);
29    }
30
31    cyclic_xor_inner(data.as_mut(), key.as_ref());
32}