Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

characters XOR with caret manipulation

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

like image 248
JDragon314159 Avatar asked Jul 06 '10 20:07

JDragon314159


2 Answers

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.

like image 166
Sjoerd Avatar answered Oct 25 '22 04:10

Sjoerd


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.

like image 35
Mark Byers Avatar answered Oct 25 '22 03:10

Mark Byers