The XOR logic operator provides a convenient way to encrypt a message. By encrypt I refer to the technique where a letter of a readable message is substituted with another letter to make the encrypted message unreadable. At least at first glance.
The basic algorithm to encrypt a message is
message letter XOR key letter = encrypted letter
and to decrypt it’s:
encrypted letter XOR key letter = message letter.
Using the XOR operator with the same key results in symmetry for encrypting and decrypting. To understand that, take a closer look at what happens at the bit level.
I want to encrypt the letter A with the key letter of K.
A is 0x41 or 0100 0001 and K is 0x4B or 0100 1011.
A 0100 0001
K 0100 1011
XOR 0000 1010
So my encrypted letter is 0x0A. Given that value and my key of K, I can run the same process to get the message back.
Ct 0000 1010
K 0100 1011
XOR 0100 0001
Why does it work? Look at the four possibilities:
A xor K = Ct xor K = A
1 1 0 1 1
1 0 1 0 1
0 1 1 1 0
0 0 0 0 0
For each of the four possibilities, using XOR with the same key value brings you back to the original message.
Here is some sample code in C/C++.
// The standard library includes the system function.
printf("Encrypt Message Using XOR\n\n");
char msg = 'A';
char key = 'K';
crypto = msg ^ key;
printf("XOR of msg (%X) and key (%X) results in %X.\n\n", msg, key, crypto);
msg = crypto ^ key;
printf("XOR of crypto (%X) and key (%X) results in %X.\n\n", crypto, key, msg);
// Keep console window open.
// Return some value.
} // end main