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