sharp_edges
sharp_edges

Reputation: 1

XOR Encryption issues... Total Beginner

As a total beginner I have been attempting to write some code for XOR encryption in C++

The problem I am having is that when decrypted only half of the message actually is correctly translated

If anyone could tell me what is going wrong and also how to fix this I would greatly appreciate it

I have also attached what is shown on the console displaying the error Qoóß®ó»¥Á╝©®50¤ä┌Ð╬┘ð╝ non-encrypte[_í®┐┐¡½®╠Press any key to continue . . .

My code is as follows;

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    char string[] = "non-encrypted_message";
    char key[] = "A";
    for (int i = 0; i < sizeof(string); i++)
    {
        string[i] = string[i] ^ key[i];     //Performing the encryption with XOR operator
        cout << string[i];                  //Output of encrypted message

    }
    cout << "\n";

    for (int j = 0; j < sizeof(string); j++)
    {
        string[j] = string[j] ^ key[j];
        cout << string[j];
    }
    cout << "\n";
    return 0;
}

Upvotes: 0

Views: 80

Answers (2)

Neil Kirk
Neil Kirk

Reputation: 21763

key has a size of only 2 (including the terminating character), yet you index it in your loops, causing it to go out of bounds. Either make it a single char and don't index it, or make sure the array is large enough. I suggest using std::string or std::array or std::vector which good debuggers will bounds-check for you.

Upvotes: 2

Yury
Yury

Reputation: 116

Declare key as char and don't use index on it.

char key = 'A';
...
string[i] = string[i] ^ key;

Upvotes: 1

Related Questions