cryptopals

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

1-2.rs (950B)


      1 use cryptopals::utils::read_buffer;
      2 
      3 fn main() -> Result<(), Box<dyn std::error::Error>> {
      4     println!("Enter first buffer");
      5     let first = hex_to_bytes(&read_buffer()?);
      6     println!("Enter second buffer");
      7     let second = hex_to_bytes(&read_buffer()?);
      8     if first.len() != second.len() {
      9         return Err("buffer length is not matched!".into());
     10     }
     11     println!("xor answer is {}", bytes_to_hex(&xor(&first, &second)));
     12     Ok(())
     13 }
     14 fn hex_to_bytes(hex: &str) -> Vec<u8> {
     15     hex.as_bytes()
     16         .chunks(2)
     17         .map(|chunk| {
     18             let s = std::str::from_utf8(chunk).unwrap();
     19             u8::from_str_radix(s, 16).expect("Invalid hex")
     20         })
     21         .collect()
     22 }
     23 fn bytes_to_hex(bytes: &[u8]) -> String {
     24     bytes.iter().map(|b| format!("{:02x}", b)).collect()
     25 }
     26 fn xor(first: &[u8], second: &[u8]) -> Vec<u8> {
     27     first
     28         .iter()
     29         .zip(second.iter())
     30         .map(|(a, b)| a ^ b)
     31         .collect()
     32 }