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,907 questions

51,839 answers

573 users

How to use XOR to encrypt and decrypt a string in C++

2 Answers

0 votes
#include <iostream>
#include <string>

// Function to encrypt or decrypt a string using XOR
std::string xorCipher(const std::string& input, char key) {
    std::string output = input;
    
    for (size_t i = 0; i < input.size(); i++) {
        output[i] ^= key; // XOR each character with the key
    }
    
    return output;
}

int main() {
    std::string text = "May the Force be with you.";
    char key = 'K'; // Encryption/Decryption key

    // Encrypt the string
    std::string encrypted = xorCipher(text, key);
    std::cout << "Encrypted: \n" << encrypted << std::endl;

    // Decrypt the string (using the same function)
    std::string decrypted = xorCipher(encrypted, key);
    std::cout << "Decrypted: \n" << decrypted << std::endl;
}



/*
run:

Encrypted: 
$9(.k).k<"?#k2$>e
Decrypted: 
May the Force be with you.

*/

 



answered Aug 16, 2025 by avibootz
0 votes
#include <iostream>
#include <string>

// Function to encrypt or decrypt a string using XOR with a string key
std::string xorCipher(const std::string& input, const std::string& key) {
    std::string output = input;

    for (size_t i = 0; i < input.size(); i++) {
        output[i] ^= key[i % key.size()]; // XOR with cyclic key character
    }

    return output;
}

int main() {
    std::string text = "May the Force be with you.";
    std::string key = "Obelus"; // String key

    // Encrypt the string
    std::string encrypted = xorCipher(text, key);
    std::cout << "Encrypted:\n" << encrypted << std::endl;

    // Decrypt the string (using the same function)
    std::string decrypted = xorCipher(encrypted, key);
    std::cout << "Decrypted:\n" << decrypted << std::endl;
}




/*
run:

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

*/

 



answered Aug 16, 2025 by avibootz
...