DEV Community

Cover image for CryptoPals Crypto Challenges Using Rust: Implement repeating-key XOR
Naveen ⚡
Naveen ⚡

Posted on

CryptoPals Crypto Challenges Using Rust: Implement repeating-key XOR

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

Context 💡

Another very easy challenge. We're given an English text -
Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal

and the key ICE. Note that the text contains a newline char too.

We just have to repeat the key chars to make it's length equal to given message/text & XOR repeated key with it. The final result should be hex-encoded. So,

Burning 'em.....cymbal ^ ICEICEICE...ICE = 0b3637272a2.....282f
Enter fullscreen mode Exit fullscreen mode

Code 🕶

Like previous challenges we'll convert the texts to bytes to perform XOR operation byte-by-byte. And convert the resulted XOR bytes to hex using hex crate:

pub fn repeated_key_xor(message: &str, key: &str) -> String {
    let key_seq: String = key.chars().cycle().take(message.len()).collect::<String>();

    let key_bytes = key_seq.as_bytes();
    let msg_bytes = message.as_bytes();

    let xor_bytes: Vec<u8> = msg_bytes
        .iter()
        .zip(key_bytes.iter())
        .map(|(&b1, &b2)| b1 ^ b2)
        .collect();

    hex::encode(xor_bytes)
}
Enter fullscreen mode Exit fullscreen mode

This was it for this challenge.

See code on Github

Find me on:
Twitter - @heyNvN

naveeen.com

Discussion (0)