DEV Community

Cover image for CryptoPals Crypto Challenges Using Rust: Fixed XOR
Naveen ⚡
Naveen ⚡

Posted on • Edited on

CryptoPals Crypto Challenges Using Rust: Fixed XOR

This is Challenge 2 of Cryptopals challenges implemented in Rust language.

Context

Given two hex encoded strings of similar length we have to return xor of it.
XOR (or, Exclusive OR) is a binary operation (like AND, OR) on bits. XOR gives true/1 as when the two inputs differ, otherwise false/0:

|  A  |  B  |XOR(A^B)|
|-----|-----|--------|
|  0  |  0  |    0   |
|  0  |  1  |    1   |
|  1  |  0  |    1   |
|  1  |  1  |    0   |
Enter fullscreen mode Exit fullscreen mode

So, theoretically you can convert hex to binary and xor them to get output, like:

10110011 ^ 01101011 = 11011000
Enter fullscreen mode Exit fullscreen mode

To solve the challenge with Rust, we can make use of hex crate to decode hex strings to bytes vec, zip the two vecs, then perform xor byte by byte to get XORed bytes. And finally encode xored bytes to hex:

use hex::{decode, encode};

pub fn fixed_xor(hex1: &str, hex2: &str) -> String {
    let bytes1 = decode(hex1).unwrap();
    let bytes2 = decode(hex2).unwrap();

    let xor_bytes: Vec<u8> = bytes1
        .iter()
        .zip(bytes2.iter())
        .map(|(&b1, &b2)| b1 ^ b2)
        .collect();
    encode(xor_bytes)
}
Enter fullscreen mode Exit fullscreen mode

And we're done.

See the code on Github.

Find me on:
Twitter - @heyNvN

naveeen.com

Top comments (0)