From f69fea769f64e0f595be6aa0b737782c481e8dec Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sat, 26 Mar 2022 19:57:45 -0400 Subject: [PATCH] Implement guess key size. --- src/bytes_base64.rs | 4 ++-- src/set1.rs | 30 ++++++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/bytes_base64.rs b/src/bytes_base64.rs index e3b93ac..8c0b6fa 100644 --- a/src/bytes_base64.rs +++ b/src/bytes_base64.rs @@ -35,7 +35,7 @@ impl BytesBase64 { pub fn to_bytes(&self) -> Bytes { let BytesBase64(v) = self; - fn chunk_to_bytes(c: &[u8]) -> Vec { + fn to_bytes(c: &[u8]) -> Vec { let mut v = c.to_vec(); // pad with bytes for conversion while v.len() < 4 { @@ -52,7 +52,7 @@ impl BytesBase64 { } result } - Bytes(v.chunks(4).map(|c| chunk_to_bytes(c)).flatten().collect()) + Bytes(v.chunks(4).map(|c| to_bytes(c)).flatten().collect()) } pub fn from_base64(s: &str) -> BytesBase64 { diff --git a/src/set1.rs b/src/set1.rs index 20c0cac..9583601 100644 --- a/src/set1.rs +++ b/src/set1.rs @@ -100,7 +100,33 @@ pub fn challenge6() { _write("data/6.txt", &bytes_base64); } + fn rate(Bytes(v): &Bytes, size: usize) -> f32 { + let (mut rating, mut iterations) = (0, 0); + for c in v.chunks(size * 2) { + if c.len() < size * 2 { + break; + } + let (a, b) = c.split_at(size); + rating += Bytes::hemming(&Bytes(a.to_vec()), &Bytes(b.to_vec())); + iterations += 1; + } + (rating as f32 / iterations as f32) / size as f32 + } + + fn guess_key_size(bytes: &Bytes) -> usize { + let (mut lowest_rating, mut lowest_size) = (f32::MAX, 0); + for key_size in 2..40 { + let rating = rate(&bytes, key_size); + if rating < lowest_rating { + lowest_rating = rating; + lowest_size = key_size; + } + } + lowest_size + } + _test_roundtrip(); - let _bytes = read("data/6.txt"); - println!("[open] Challenge 6: {}", 0); + let bytes = read("data/6.txt"); + let key_size = guess_key_size(&bytes); + println!("[open] Challenge 6: guessed_key_size={}", key_size); }