Reputation: 41
I am trying to implement a simple XOR Encryption using a number, of type long
. Unfortunately, some of the numbers return some symbols that decrypting them gives a whole different text than the one entered.
For example, encrypting a text 'hello world'
with the key '5105105105'
returns this '��'
. To decrypt it back with the same key, it returns this '>nl wor>nl'
. I am not sure why is it doing this.
This is my code:
string encDec(string str, long key) {
string output = str;
for (int i = 0; i < str.size(); i++)
output[i] = str[i] ^ key;
return output;
}
What am I doing wrong here?
Upvotes: 0
Views: 1166
Reputation: 94058
Let's look at: output[i] = str[i] ^ key;
What this does is that it first retrieves a character from the string str
at index i
. A character in std::string
is equivalent to an 8 bit byte.
Then this byte is being coaxed into a long
using an implicit widening conversion to match the left key
.
After that all the bits are XOR'ed with the key, performing the "encryption". I've put this in quotes because repeated use of the key with a XOR cipher is of course not secure.
Finally an implicit narrowing conversion is used to assign this long value to the char array again.
In other words, you can see this as performing: output[i] = (char) ((long) str[i] ^ key;
if you make the conversions explicit. Note that many bits are first XOR'ed, and then thrown away during the narrowing conversion; probably not what you want as those key bits are basically ignored.
Of course if you XOR with random bits then what you get in return is a random binary pattern. This kind of pattern may not consist of printable characters. You either have to store or send those as binary values, or you must first convert them back to printable text. Usually we do that using hex or base 64 encoding of the bytes.
Modern cryptography operates on bits and bytes. Classical ciphers such as Caesar and Vigenere ciphers do operate on text and gave text as output. In the end, XOR is an operation on bits, not on characters of a text.
Upvotes: 2