Day 14

A Rust Message Encryptor

Try it!

The program is embedded below via the Rust Playground. Before running, click the Stdin tab inside the embed and enter your message on the first line and your key on the second line.



Open in full page

Description


A Rust CLI program that takes a message and a key and encrypts the message using XOR — a simple symmetric cipher where each byte of the message is XOR'd with the corresponding byte of the key (cycling the key if it's shorter than the message). The result is printed as a hex string. A good exercise for learning how Rust handles strings, iterators, and byte-level operations.

View the source code


use std::io;

fn main() {
    println!("Enter the message to encrypt:");
    let mut message = String::new();
    io::stdin().read_line(&mut message).expect("Failed to read");
    let message = message.trim_end();

    println!("Enter the encryption key:");
    let mut key = String::new();
    io::stdin().read_line(&mut key).expect("Failed to read");
    let key = key.trim_end();

    if key.is_empty() {
        eprintln!("Key cannot be empty.");
        return;
    }

    let message_bytes = message.as_bytes();
    let key_bytes = key.as_bytes();
    let encrypted: Vec<u8> = message_bytes
        .iter()
        .enumerate()
        .map(|(i, &b)| b ^ key_bytes[i % key_bytes.len()])
        .collect();

    let hex: String = encrypted.iter().map(|b| format!("{:02x}", b)).collect();
    println!("Encrypted (hex): {}", hex);
}

Previous Day
Next Day