Implement guess key size.

This commit is contained in:
2022-03-26 19:57:45 -04:00
parent 1e84f2cb58
commit f69fea769f
2 changed files with 30 additions and 4 deletions

View File

@@ -35,7 +35,7 @@ impl BytesBase64 {
pub fn to_bytes(&self) -> Bytes {
let BytesBase64(v) = self;
fn chunk_to_bytes(c: &[u8]) -> Vec<u8> {
fn to_bytes(c: &[u8]) -> Vec<u8> {
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 {

View File

@@ -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);
}