ATTENTION READERS! Lucky's VB Gaming Site is no longer active. For updated game programming information and tutorials, please visit The Game Programming Wiki!
Basic Encryption
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 are true. Wait, that sounds confusing :)
An illustration is in order!
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 the source code for an example of string
encryption.