Question

Description:
I am trying to write a simple program for fun that will read in a phrase then xor encrypt it then output the encrypted phrase to the terminal window. See code below for more info.

code:
#include #include using namespace std;

int main ()
{
string mystr;
cout << "What's the phrase to be Encrypted? ";

char key[11]="ABCDEFGHIJK";  //The Encryption Key, for now its generic
getline(cin, mystr);

string result;

for (int i=0; i<10; i++) {
    result.push_back(mystr[i] ^ key[i]);
    cout << result[i];
}
cout << "\n";
return 0;
}

Results:
The code above works however When I input a very long string it only encrypts the first 10 characters (I think). I would like to be able to input a large string encrypt it with the 11 bit key then output it to the terminal. How do I do this?

Also:
I have asked a question that is a pre-cursor to this question located here: String input xor encryption program

help:
If you have any idea how to fix this could you please give an example of either what Im missing or what I need with explanation.

Was it helpful?

Solution

You're only looping over 10 characters as defined by your for loop for (int i=0; i<10; i++). You want to loop over your entire string length and then XOR with your key mod 11.

for (int i=0; i<mystr.size(); i++) {
    result.push_back(mystr[i] ^ key[i%11]);
    cout << result[i];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top