C++ XOR Encryption Cipher for Secret Messages

Ever wanted to send secret messages to your friends? Using C++ and the XOR ^ operator and the AND & operator you can make secure a encryption that only people with your source code can use.

You can change the encryption to your customized preference as well. You can even | OR it with some other number.

You can also create two programs, one called Encrypt.exe, the other Decrypt.exe and send one or the other to your friend. Of course this isn't the most secure encryption algorithm but it is good enough for most general purposes.

Use cin and cout to get user input and create your Decryption and Encryption separate programs.

#include<iostream>
using namespace std;

string XOR_Encryption(string toBeEncrypted, string sKey){
    string sEncrypted(toBeEncrypted);
    unsigned int iKey(sKey.length()), iIn(toBeEncrypted.length()), x(0);

    for(unsigned int i = 0; i < iIn; i++){
        sEncrypted[i] = toBeEncrypted[i] ^ sKey[x] & 10;
        if(++x == iKey){ x = 0; }
    }
    return sEncrypted;
}


int main(){
    string sInput("This is a top secret unencrypted message about to be encrypted.");
    string sPrivateKey("private_encryption_key");

    cout << "Unencrypted Message: " << sInput << endl << endl;
    sInput = XOR_Encryption(sInput, sPrivateKey);
    cout << "Ciphered / Encrypted Message: " << sInput << endl << endl;
    sInput = XOR_Encryption(sInput, sPrivateKey);
    cout << "Decrypted Message: " << sInput << endl;

    cin.get();
    return 0;
}

The XOR_Encryption function basically loops through the key and the toBeEncrypted strings ^ XORing each character in toBeEncrypted with each character in the key, and using the AND operator & , it adds an extra level of security so no one can simply take the ASCII character and XOR it if they have your key without knowing about the & 10.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.