344 Part II Programming Fundamentals
Code = CShort(strCode)
'read encrypted numbers
AllText = My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
AllText = AllText.Trim
'split numbers in to an array based on space
Numbers = AllText.Split(" ")
'loop through array
For i = 0 To Numbers.Length - 1
Number = CShort(Numbers(i)) 'convert string to number
ch = Chr(Number Xor Code) 'convert with Xor
Decrypt = Decrypt & ch 'and build string
Next
txtNote.Text = Decrypt 'then display converted string
lblNote.Text = OpenFileDialog1.FileName
txtNote.Select(0, 0) 'remove text selection
txtNote.Enabled = True 'allow text cursor
mnuCloseItem.Enabled = True 'enable Close command
mnuOpenItem.Enabled = False 'disable Open command
Catch ex As Exception
MsgBox("An error occurred." & vbCrLf & ex.Message)
End Try
End If
When the user clicks the Open Encrypted File command, this event procedure opens the
encrypted file, prompts the user for an encryption code, and displays the translated file in
the text box object. The ReadAllText method reads the encrypted file. The Split method splits
the numbers as strings into an array and uses the space as a separator. The For loop reads
each string in the array, converts the string to a number, and stores it in the Number short
integer variable. The Number variable is then combined with the Code variable by using the
Xor operator, and the result is converted to a character by using the Chr function. These
characters (stored in the ch variable of type Char) are then concatenated with the Decrypt
string variable, which eventually contains the entire decrypted text file, as shown here:
ch = Chr(Number Xor Code) 'convert with Xor
Decrypt = Decrypt & ch 'and build string
Encryption techniques like this are useful, and they can also be very instructional. Because
encryption relies so much on string-processing techniques, it’s a good way to practice
a fundamental and important Visual Basic programming skill. As you become more
experienced, you can also use the encryption services provided by the .NET Framework to
add much more sophisticated security and cryptography services to your programs. For
an introduction to these topics, search for “Cryptographic Tasks” in the Visual Studio Help
documentation. Because these services rely somewhat on your understanding of classes,
containers, and Internet transactions, I recommend that you finish the chapters in Parts III
and IV of this book before you experiment with them.
Well, now—congratulations! If you’ve worked from Chapters 5 to here, you’ve completed the
programming fundamentals portion of this book, and you are now ready to focus specifically
on creating professional-quality user interfaces in your programs. You have come a long way