Last active
July 26, 2018 23:04
-
-
Save dresswithpockets/b247db4bb5330be994e91d33c09caf84 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn challenge3() { | |
let valid_chars: Vec<char> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.- ".chars().collect(); | |
let repeated_char_score = 1; | |
let mut input = String::new(); | |
println!("Single-byte XOR cipher"); | |
print!("encoded string> "); | |
io::stdout().flush().unwrap(); | |
io::stdin().read_line(&mut input).expect("Failed to read line"); | |
// no line ending please! | |
input.pop(); | |
let input_bytes = hex_decode(&input); | |
let range = 0..255; | |
let mut scores: Vec<(u8, i32, String)> = range.filter_map(|byte| { | |
let text = byte_xor(&input_bytes, byte); | |
if let Ok(text_str) = String::from_utf8(text) { | |
let text_chars: Vec<char> = text_str.chars().collect(); | |
let text_score = score_text(&text_chars, &valid_chars, repeated_char_score); | |
Some((byte, text_score, text_str)) | |
} | |
else { | |
None | |
} | |
}).collect(); | |
// sort by score | |
scores.sort_by(|a, b| b.1.cmp(&a.1)); | |
println!("{} on byte {} from text '{}'", scores[0].1, scores[0].0, scores[0].2); | |
} | |
pub fn challenge4() { | |
let valid_chars: Vec<char> = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.- ".chars().collect(); | |
let repeated_char_score = 1; | |
let mut input = String::new(); | |
println!("Detect single-character XOR"); | |
print!("file path> "); | |
io::stdout().flush().unwrap(); | |
io::stdin().read_line(&mut input).expect("Failed to read line"); | |
// no line ending please! | |
input.pop(); | |
let file = BufReader::new(File::open(input).unwrap()); | |
let mut file_scores: Vec<(String, u8, i32, String)> = file.lines().map(|line| { | |
let input_str: String = line.unwrap(); | |
let input_bytes = hex_decode(&input_str); | |
let range = 0..255; | |
let mut scores: Vec<(u8, i32, String)> = range.filter_map(|byte| { | |
let text = byte_xor(&input_bytes, byte); | |
if let Ok(text_str) = String::from_utf8(text) { | |
let text_chars: Vec<char> = text_str.chars().collect(); | |
let text_score = score_text(&text_chars, &valid_chars, repeated_char_score); | |
Some((byte, text_score, text_str)) | |
} | |
else { | |
None | |
} | |
}).collect(); | |
// sort by score | |
scores.sort_by(|a, b| b.1.cmp(&a.1)); | |
// error here on `scores[0].2` | |
(input_str, scores[0].0, scores[0].1, scores[0].2) | |
}).collect(); | |
file_scores.sort_by(|a, b| b.2.cmp(&a.2)); | |
println!("{} on byte {} from text '{}' in string '{}'", file_scores[0].2, file_scores[0].1, file_scores[0].3, file_scores[0].0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment