I mentioned that one use of bit operations is encryption. Xor encryption is a popular and simple way to "encrypt" a file. In my article, Very Simple Encryption using VB.NET, I show you a better way using string manipulation instead. But Xor encryption is so common that it deserves to at least be explained.
Encrypting a text string means translating it into another text string that doesn't have an obvious relationship to the first one.
You also need a way to decrypt it again. Xor encryption translates the binary ASCII code for each character in the string into another character using the Xor operation. In order to do this translation, you need another number to use in the Xor. This second number is called the key.
Xor encryption is called a "symmetric algorithm". This means that we can use the encryption key as the decryption key too.
Let's use "A" as the key and encrypt the word "Basic". The ASCII code for "A" is:
0100 0001 (decimal 65)
The ASCII code for Basic is:
B - 0100 0010
a - 0110 0001
s - 0111 0011
i - 0110 1001
c - 0110 0011
The Xor of each of these is:
0000 0011 - decimal 3
0010 0000 - decimal 32
0011 0010 - decimal 50
0010 1000 - decimal 40
0010 0010 - decimal 34
This little routine does the trick:
-- Xor Encryption --
Dim i As Short
ResultString.Text = ""
Dim KeyChar As Integer
KeyChar = Asc(EncryptionKey.Text)
For i = 1 To Len(InputString.Text)
ResultString.Text &= _
Chr(KeyChar Xor _
Asc(Mid(InputString.Text, i, 1)))
Next
The result can be seen in this illustration:
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
To reverse the encryption, just copy and paste the string from the Result TextBox back into the String TextBox and click the button again.
Another example of something you can do with bitwise operators is to swap two Integers without declaring a third variable for temporary storage. This is the kind of thing they used to do in assembly language programs years ago. It's not too useful now, but you might win a bet someday if you can find someone who doesn't believe you can do it. In any case, if you still have questions about how Xor works, working through this should put them to rest. Here's the code:
Dim FirstInt As Integer
Dim SecondInt As Integer
FirstInt = CInt(FirstIntBox.Text)
SecondInt = CInt(SecondIntBox.Text)
FirstInt = FirstInt Xor SecondInt
SecondInt = FirstInt Xor SecondInt
FirstInt = FirstInt Xor SecondInt
ResultBox.Text = "First Integer: " & _
FirstInt.ToString & " - " & _
"Second Integer: " & _
SecondInt.ToString
And here's the code in action:
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
Figuring out exactly why this works will be left as "as an exercise for the student".
On the next page, we reach the goal: General Bit Manipulation
next post