6

CryptoPals Crypto Challenges Using Rust: Fixed XOR

 2 years ago
source link: https://dev.to/thenvn/cryptopals-crypto-challenges-using-rust-fixed-xor-4e96
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK