cryptopals-rust/set1/challenge2_fixed_xor/src/main.rs

50 lines
1.2 KiB
Rust

use common::fixed_xor_cipher;
use log::error;
use rustc_serialize::hex::{FromHex, ToHex};
use std::io::{stdin, BufRead};
struct Pairwise<T: Iterator>(T);
impl<T> Iterator for Pairwise<T>
where
T: Iterator,
{
type Item = (T::Item, T::Item);
fn next(&mut self) -> Option<Self::Item> {
if let (Some(fst), Some(snd)) = (self.0.next(), self.0.next()) {
Some((fst, snd))
} else {
None
}
}
}
fn main() {
env_logger::init();
for (line1, line2) in Pairwise(stdin().lock().lines().filter_map(|x| x.ok())) {
match (line1.from_hex(), line2.from_hex()) {
(Ok(v1), Ok(v2)) => println!(
"{}",
fixed_xor_cipher(v1.as_slice(), v2.as_slice()).to_hex()
),
(Err(e), _) => error!("{}", e),
(_, Err(e)) => error!("{}", e),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn challenge2_fixed_xor() {
let v1 = "1c0111001f010100061a024b53535009181c".from_hex().unwrap();
let v2 = "686974207468652062756c6c277320657965".from_hex().unwrap();
let r = fixed_xor_cipher(v1.as_slice(), v2.as_slice()).to_hex();
assert_eq!(r, "746865206b696420646f6e277420706c6179");
}
}