How to use XOR to encrypt and decrypt a string in Rust

2 Answers

0 votes
fn xor_encrypt_decrypt(input: &str, key: u8) -> String {
    input
        .bytes()
        .map(|byte| byte ^ key) // XOR each byte with the key
        .map(|byte| byte as char) // Convert back to char
        .collect() // Collect into a String
}

fn main() {
    let s = "May the Force be with you.";
    let key: u8 = 18; // Encryption and decryption key

    // Encrypt the string
    let encrypted = xor_encrypt_decrypt(s, key);
    println!("Encrypted: {}", encrypted);

    // Decrypt the string (using the same key)
    let decrypted = xor_encrypt_decrypt(&encrypted, key);
    println!("Decrypted: {}", decrypted);
}




/*
run:

Encrypted: _sk2fzw2T}`qw2pw2e{fz2k}g<
Decrypted: May the Force be with you.

*/

 



answered Aug 16, 2025 by avibootz
0 votes
fn xor_encrypt_decrypt(input: &str, key: &str) -> String {
    let key_bytes = key.as_bytes();
    input
        .bytes()
        .enumerate()
        .map(|(i, byte)| byte ^ key_bytes[i % key_bytes.len()])
        .map(|byte| byte as char)
        .collect()
}

fn main() {
    let s = "May the Force be with you.";
    let key = "Obelus"; // String key for XOR operation

    // Encrypt the string
    let encrypted = xor_encrypt_decrypt(s, key);
    println!("Encrypted: {}", encrypted);

    // Decrypt the string (using the same key)
    let decrypted = xor_encrypt_decrypt(&encrypted, key);
    println!("Decrypted: {}", decrypted);
}




/*
run:

Encrypted: L*B#*   BU&L:L
Decrypted: May the Force be with you.

*/

 



answered Aug 16, 2025 by avibootz

Related questions

...