Implement set 1 challenge 2.

This commit is contained in:
2022-03-25 19:53:54 -04:00
parent 4a077ade98
commit c33686220d
2 changed files with 52 additions and 15 deletions

View File

@@ -1,7 +1,11 @@
mod set1;
use crate::set1::challenge1;
use crate::set1::challenge2;
use crate::set1::challenge3;
fn main() {
challenge1();
challenge2();
challenge3();
}

View File

@@ -1,6 +1,8 @@
use std::fmt::Write;
use std::num::ParseIntError;
use std::str;
#[derive(PartialEq, PartialOrd, Debug)]
pub struct HexBytes(Vec<u8>);
pub struct Base64Bytes(Vec<u8>);
@@ -88,9 +90,9 @@ impl HexBytes {
)
}
pub fn from_str(s: &str) -> Result<HexBytes, String> {
pub fn from_str(s: &str) -> HexBytes {
if s.len() % 2 != 0 {
return Err(String::from("Input string has uneven number of characters"));
panic!("Input string has uneven number of characters");
}
let bytes_result: Result<Vec<u8>, ParseIntError> = (0..s.len())
@@ -99,24 +101,55 @@ impl HexBytes {
.collect();
match bytes_result {
Ok(b) => Ok(HexBytes(b)),
Err(_) => Err(String::from("Could not convert all digit pairs to hex.")),
Ok(b) => HexBytes(b),
Err(_) => panic!("Could not convert all digit pairs to hex."),
}
}
pub fn to_utf8_string(&self) -> String {
let HexBytes(v) = self;
String::from(str::from_utf8(&v).unwrap())
}
pub fn to_hex_string(&self) -> String {
let HexBytes(v) = self;
let mut r = String::new();
for e in v.iter() {
write!(r, "{:02x}", e);
}
r
}
fn xor(HexBytes(a): &HexBytes, HexBytes(b): &HexBytes) -> HexBytes {
HexBytes(
Iterator::zip(a.iter(), b.iter())
.map(|z| *(z.0) ^ *(z.1))
.collect(),
)
}
}
pub fn challenge1() {
let input = HexBytes::from_str("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d");
let expected = String::from("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t");
match input {
Ok(bytes) => {
let output = bytes.to_base64();
if output.to_string() != expected {
println!("HexBytes.to_base64 failed.")
} else {
println!("[okay] Challenge 1: {}", output);
}
}
Err(e) => println!("Error: {}", e),
};
let result = input.to_base64();
if result.to_string() == expected {
println!("[okay] Challenge 1: {}", result);
} else {
println!("[fail] Challenge 1")
}
}
pub fn challenge2() {
let a = HexBytes::from_str("1c0111001f010100061a024b53535009181c");
let b = HexBytes::from_str("686974207468652062756c6c277320657965");
let r = HexBytes::xor(&a, &b);
let e = HexBytes::from_str("746865206b696420646f6e277420706c6179");
if r == e {
println!("[okay] Challenge 2: {}", r.to_hex_string());
} else {
println!("[fail] Challenge 2")
}
}
pub fn challenge3() {}