Skip to content

Instantly share code, notes, and snippets.

@dresswithpockets
Last active July 26, 2018 23:04
Show Gist options
  • Save dresswithpockets/b247db4bb5330be994e91d33c09caf84 to your computer and use it in GitHub Desktop.
Save dresswithpockets/b247db4bb5330be994e91d33c09caf84 to your computer and use it in GitHub Desktop.
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