Implement Base64 read.

This commit is contained in:
2022-03-26 13:40:28 -04:00
parent 7a1c62c47e
commit b490b67d55
5 changed files with 126 additions and 19 deletions

View File

@@ -1,7 +1,7 @@
#![allow(dead_code)]
use crate::bytes::Bytes;
use crate::bytes_base64::BytesBase64;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::io::{BufRead, BufReader, Write};
use std::str;
pub fn challenge1() {
@@ -37,24 +37,24 @@ pub fn challenge3() {
}
pub fn challenge4() {
pub fn read_to_vector(path: &str) -> Vec<Bytes> {
let file = File::open(path).unwrap();
fn read(path: &str) -> Vec<Bytes> {
let file = std::fs::File::open(path).unwrap();
let br = BufReader::new(file);
br.lines()
.map(|line| Bytes::from_hex(&line.unwrap()))
.collect()
}
let bs = read_to_vector("data/4.txt");
let mut h: Vec<Bytes> = vec![];
let bytes_vector = read("data/4.txt");
let mut xored_bytes_vector: Vec<Bytes> = vec![];
for i in 32..=127 {
for b in bs.iter() {
h.push(Bytes::xor_byte(b, i));
for bytes in bytes_vector.iter() {
xored_bytes_vector.push(Bytes::xor_byte(bytes, i));
}
}
h.sort_by(|a, b| a.ascii_score().partial_cmp(&b.ascii_score()).unwrap());
let r = h[h.len() - 1].to_utf8();
println!("[okay] Challenge 4: {}", r.trim());
xored_bytes_vector.sort_by(|a, b| a.ascii_score().partial_cmp(&b.ascii_score()).unwrap());
let result = xored_bytes_vector.last().unwrap().to_utf8();
println!("[okay] Challenge 4: {}", result.trim());
}
pub fn challenge5() {
@@ -72,6 +72,28 @@ pub fn challenge5() {
}
pub fn challenge6() {
// next: base64bytes to hexbytes
println!("[open] Challenge 6: xxx");
fn read(path: &str) -> BytesBase64 {
let s = std::fs::read_to_string(path).unwrap();
BytesBase64::from_base64(&s)
}
fn write(path: &str, bytes_base64: &BytesBase64) {
let width = 60;
let bytes = bytes_base64.to_string();
let mut output_vec = vec![];
for e in Iterator::zip(bytes.as_bytes().iter(), 0..bytes.len()) {
if e.1 % width == 0 && e.1 > 0 {
output_vec.push('\n' as u8)
}
output_vec.push(*e.0);
}
let mut f = std::fs::File::create(path).unwrap();
f.write(&output_vec).unwrap();
}
let bytes_base64 = read("data/6.txt");
write("data/6_out.txt", &bytes_base64);
println!("[open] Challenge 6");
}