-
Notifications
You must be signed in to change notification settings - Fork 74
/
xor.rs
36 lines (34 loc) · 839 Bytes
/
xor.rs
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
/// XOR cipher
///
/// # Arguments
///
/// * `text` - A string slice that holds the text to be ciphered.
/// * `key` - A u8 that holds the key to be used for ciphering.
///
/// # Returns
///
/// * A String that holds the ciphered text.
///
/// # Example
///
/// ```rust
/// use rust_algorithms::ciphers::xor;
///
/// let test_string = "The quick brown fox jumps over the lazy dog";
/// let ciphered_text = xor(test_string, 64);
///
/// assert_eq!(test_string, xor(&ciphered_text, 64));
/// ```
pub fn xor(text: &str, key: u8) -> String {
text.chars().map(|c| ((c as u8) ^ key) as char).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple() {
let test_string = "test string";
let ciphered_text = xor(test_string, 32);
assert_eq!(test_string, xor(&ciphered_text, 32));
}
}