Finish challenge 20 statistical CTR.

This commit is contained in:
2022-07-29 09:20:59 -04:00
parent 3248609119
commit 6485a2f068
5 changed files with 112 additions and 9 deletions

View File

@@ -268,5 +268,38 @@ pub fn challenge19() {
}
pub fn challenge20() {
println!("[xxxx] Challenge 20: TBD");
fn read(path: &str) -> Vec<Bytes> {
let file = std::fs::File::open(path).unwrap();
let br = BufReader::new(file);
br.lines()
.map(|line| BytesBase64::from_base64(&line.unwrap()).to_bytes())
.collect()
}
fn attack(ciphers: Vec<Bytes>) -> Vec<Bytes> {
let min_cipher_len = ciphers.iter().map(|c| c.len()).min().unwrap_or(0);
let mut key: Vec<u8> = vec![];
for byte_index in 0..min_cipher_len {
let bytes = Bytes(ciphers.iter().map(|c| c.0[byte_index]).collect());
let key_char = Bytes::guess_key(&bytes);
key.push(key_char);
}
let key = Bytes(key);
ciphers
.iter()
.map(|cipher| Bytes::xor(&key, cipher))
.collect()
}
let plaintexts = read("data/20.txt");
let key = Bytes::from_utf8("YELLOW SUBMARINE");
let encrypt = |plaintext: &Bytes| -> Bytes { ctr::encrypt(&key, 0, plaintext) };
let ciphers: Vec<Bytes> = plaintexts.iter().map(|ct| encrypt(&ct)).collect();
let plaintexts = attack(ciphers);
println!("[okay] Challenge 20: {}", plaintexts[0].to_utf8());
}
pub fn challenge21() {
println!("[xxxx] Challenge 21: TBD");
}