Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

340 Part II Programming Fundamentals


This type of simple encryption might be all you need to conceal the information in your text
files. However, files encrypted in this way can easily be decoded. By searching for possible
equivalents of common characters such as the space character, determining the ASCII shift
required to restore the common character, and running the conversion for the entire text
file, a person experienced in encryption could readily decipher the file’s content. Also, this
sort of encryption doesn’t prevent a malicious user from physically tampering with the
file—for example, simply by deleting it if it’s unprotected on your system or by modifying
it in significant ways. But if you just want to hide information quickly, this simple encryption
scheme should do the trick.

One Step Further: Using the Xor Operator


The preceding encryption scheme is quite safe for text files because it shifts the ASCII
character code value up by just 1. However, you’ll want to be careful about shifting ASCII
codes more than a few characters if you store the result as text in a text file. Keep in mind
that dramatic shifts in ASCII codes (such as adding 500 to each character code) won’t
produce actual ASCII characters that can be decrypted later. For example, adding 500 to the
ASCII code for the letter A (65) would give a result of 565. This value couldn’t be translated
into a character by the Chr function and would generate an error.

One way around this problem is to convert the letters in your file to numbers when you
encrypt the file so that you can reverse the encryption no matter how large (or small)
the numbers are. If you followed this line of thought, you could then apply mathematical
functions—multiplication, logarithms, and so on—to the numbers so long as you knew how
to reverse the results.

One tool for encrypting numeric values is already built into Visual Basic. This tool is the Xor
operator, which performs the “exclusive or” operation, a function carried out on the bits that
make up the number itself. The Xor operator can be observed by using a simple MsgBox
function. For example, the program statement:

MsgBox(Asc("A") Xor 50)

would display a numeric result of 115 in a message box when the Visual Basic compiler
executes it. Likewise, the program statement:

MsgBox(115 Xor 50)

would display a result of 65 in a message box, the ASCII code for the letter A (our original
value). In other words, the Xor operator produces a result that can be reversed—if the
original Xor code is used again on the result of the first operation. This interesting behavior
of the Xor function is used in many popular encryption algorithms. It can make your secret
files more difficult to decode.
Free download pdf