1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Programming Tutorial - Low Level Operations

By David Bolton, About.com

6 of 10

A look at Xor in Lightweight Encryption

Counting 1s and 0s in binary is error prone - try 1001101011 how big is that? Instead use decimal (base 10), base 8 or base 16 to specify numbers. Each hexadecimal digit is 4 bits. Digits 0-9 are the same as their decimal equivalents in binary (0000-1001) and hexadecimal digits A-F are represented by 1010 (A) through to 1111 (F). Every byte is represented by two hexadecimal digits, a 32 bit int by 8 hexadecimal digits. Here are some values, showing decimal, hexadecimal and binary.
  • 7, 0x7, 00000111
  • 246,0xd6, 11010110
  • 1050,0x41a 010000011010
  • 98765,0x181cd, 00010100000111001101

The magical property of Xor ^

If we xor two ints a and b to get c then a ^ c gives b and b ^ c gives a.

To create an encrypted text file, "binary xor" a file of text with a value, say 255 to get an encrypted file. If we xor this with 255, we get back our original unencrypted text. As encryption schemes go, this is light weight and probably the most reinvented wheel by novice programmers. It can be made tougher by using values to xor that have at least 3 bits set instead of just 255.

In 8 bits, there are 256 different possible values- 0 to 255. There are only 36 values with 0,1, OR 2 set bits so that leaves 219 values which can be used. Stick these in an array and xor the first byte of the file against the first byte of the table, 2nd against the 2nd array value and so on.

Although light weight it is useful for hiding text strings in applications. A binary file viewer/editor lets anyone look for text strings, hidden commands, registry keys, even secret passwords. By encrypting these it makes life harder for them.

Example 3 displays the 219 values with three or more bits set, plus the remainder. It uses a similar mechanism to that PrintBinary() used in example 1.

Download Example 3.

On the next page - A look at Unions

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. A look at Xor in Lightweight Encryption

©2009 About.com, a part of The New York Times Company.

All rights reserved.