VB:Tutorials:Basic Encryption with XOR

From GPWiki
Jump to: navigation, search

Basic is right! This is not some brain-bending algorithm, in fact, you could say that it's eXtraORdinarily easy! How's that for subliminal messaging? Yes, we'll be using the XOR operator.

For those of you not familiar with XOR, I'll give you a little lesson. XOR is supposed to mean "exclusive OR". It is so called because it only returns True if one and only one of the expressions it is passed is True. Wait, that sounds confusing :) An illustration is in order!

True Xor True = False True Xor False = True False Xor True = True False Xor False = False

See? Now, the logical operations of XOR (above) are less useful to us than the bitwise operations. Observe:

1 Xor 1 = 0 1 Xor 0 = 1 0 Xor 1 = 1 0 Xor 0 = 0

This is pretty much the same as the logical operation, but watch, we can perform it on a whole bunch of bits (say... a BYTE!) at a time:

01010101  (Key)

Here comes the magic.. if we XOR again, using the value I've marked Key and the result, we obtain the original!

10101010  (Old Result)
01010101  (Key)
11111111  (!!!)

This works in all situations when the key is held constant: XOR once, you have an encrypted result. XOR again with the same key, and you get the original value. Sounds cool, but how can we apply it practically? When storing data in a binary file, it is a simple matter to XOR each byte that is read or written in order to encrypt/decrypt it. To encrypt data under other circumstances can be a little trickier. You need to coerce that data into byte form, and then back again. We'll do it with strings here:

Dim strResult As String Dim strChar1 As String * 1 Dim strChar2 As String * 1

   strChar1 = "E"
   strChar2 = "z"
   strResult = Chr(Asc(strChar1) Xor Asc(strChar2))

This code will XOR "E" with "z" by converting them to their ASCII values! Once converted to ASCII, they can be treated like bytes and XOR'ed. We can then convert back to string format using the Chr function. This method can be adapted using a For loop to encrypt complex strings using equally complex key values. Click here to download sample source code for an example of string encryption.