Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

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
...