Friday 23 March 2012

Using XOR To Encrypt Message


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.
#include <cstdlib>

int main()
{
     printf("Encrypt Message Using XOR\n\n");
     char msg = 'A';
     char key = 'K';
     char crypto;

     // Encipher.
     crypto = msg ^ key;
     printf("XOR of msg (%X) and key (%X) results in %X.\n\n", msg, key, crypto);

     // Decipher.
     msg = crypto ^ key;
     printf("XOR of crypto (%X) and key (%X) results in %X.\n\n", crypto, key, msg);
    

     // Keep console window open.
     system("pause");

     // Return some value.
     return 0;
} // end main

Output.




No comments:

Post a Comment