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

48 lines
1.2 KiB
Rust

use common::break_xor_cipher;
use log::error;
use rustc_serialize::hex::FromHex;
use std::error::Error;
use std::io::{stdin, BufRead};
fn detect_xor(input: &mut dyn BufRead) -> Result<String, Box<dyn Error>> {
let mut maxscore = 0;
let mut decrypted: Vec<u8> = vec![];
for line in input.lines() {
let ciphertext = line?.from_hex()?;
let (plaintext, score) = break_xor_cipher(ciphertext.as_slice());
if score > maxscore {
maxscore = score;
decrypted = plaintext;
}
}
Ok(String::from_utf8(decrypted)?)
}
fn main() {
env_logger::init();
match detect_xor(&mut stdin().lock()) {
Ok(s) => println!("{}", s),
Err(e) => error!("{}", e),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
#[test]
fn challenge4_detect_xor() {
let cargo_manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
let testinput = File::open(cargo_manifest_dir.join("4.txt")).unwrap();
assert_eq!(
detect_xor(&mut BufReader::new(testinput)).unwrap(),
"Now that the party is jumping\n"
);
}
}