views:

111

answers:

5

Working with exclusive-OR on bits is something which is clear to me. But here, XOR is working on individual characters. So does this mean the byte which makes up the character is being XORed? What does this look like?

#include <iostream.h>
int main()
{
  char string[11]="A nice cat";
  char key[11]="ABCDEFGHIJ";
  for(int x=0; x<10; x++)
  {
    string[x]=string[x]^key[x];
    cout<<string[x];
  }
  return 0;
}

I know bits XORed look like this:
1010
1100
0110

+6  A: 

XOR has the nice property that if you XOR something twice using the same data, you obtain the original. The code you posted is some rudimentary encryption function, which "encrypts" a string using a key. The resulting ciphertext can be fed through the same program to decrypt it.

Sjoerd
In the old days, XOR was sometimes also used for sprite animation, specially on black backgrounds, instead of the masking method (AND mask OR sprite)
ninjalj
+2  A: 

The xor on characters performs the xor operation on each corresponding bit of the two characters (one byte each).

Mark B
+5  A: 

In C and C++ strings are usually stored in memory as 8-bit char values where the value stored is the ASCII value of the character.

Your code is therefore XORing the ASCII values. For example, the second character in your output is calculated as follows:

  'B' ^ ' '
= 66 ^ 32
= 01000010 ^ 00100000
= 01100010
= 98
= 'b'

You could get a different result if you ran this code on a system which uses EBCDIC instead of ASCII.

Mark Byers
+2  A: 
So does this mean the byte which makes up the character is being XORed?

Exactly.

What does this look like?

As any other XOR :) . In ASCII "A nice cat" is (in hexadecimal)

41 20 6E 69 63 65 20 63 61 74

and ABCDEFGHIJ

41 42 43 44 45 46 47 48 49 4A

so, if you XOR each byte with each other, you get

00 62 2D 2D 26 23 67 2B 28 3E

, which is the hexadecimal representation of "\0b--&#g+(>", i.e. the string that is displayed when you run that code.

Notice that if you XOR again the resulting text you get back the text with which you started; this the reason why XOR is used often in encoding and cyphering.

Matteo Italia
A: 

This is a simple demonstration of one time pad encryption, which as you can see is quite simple and also happens to be the only provably unbreakable form of encryption. Due to it being symmetric and having a key as large as the message, it's often not practical, but it still has a number of interesting applications.. :-)

One fun thing to notice if you're not already familiar with it is the symmetry between the key and the ciphertext. After generating them, there's no distinction of which one is which, i.e. which one was created first and which was based on the plaintext xor'd with the other. Aside from basic encryption this also leads to applications in plausible deniability.

R..