DEV Community

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

Posted on • Edited on

2 2

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay