Chapter 13 Exploring Text Files and String Processing 347
To Do This
Convert text
characters to ASCII
codes
Use the Asc function. For example:
Dim Code As Short
Code = Asc("A") 'Code equals 65
Convert ASCII codes
to text characters
Use the Chr function. For example:
Dim Letter As Char
Letter = Chr(65) 'Letter equals "A"
Encrypt text Use the Xor operator and a user-defined encryption code. For example,
this code block uses Xor and a user code to encrypt the text in the txtNote
text box and to save it in the encrypt .txt file as a series of numbers:
strCode = InputBox("Enter Encryption Code")
Code = CShort(strCode)
charsInFile = txtNote.Text.Length
StreamToWrite = My.Computer.FileSystem.OpenTextFileWriter( _
SaveFileDialog1.FileName, False)
For i = 0 To charsInFile – 1
letter = txtNote.Text.Substring(i, 1)
StreamToWrite.Write(Asc(letter) Xor Code)
StreamToWrite.Write(" ")
Next
StreamToWrite.Close()
Decrypt text Request the code that the user chose to encrypt the text, and use Xor to
decrypt the text. For example, this code block uses Xor and a user code to
reverse the encryption created in the preceding example:
strCode = InputBox("Enter Encryption Code")
Code = CShort(strCode)
AllText = My.Computer.FileSystem.ReadAllText( _
OpenFileDialog1.FileName)
Numbers = AllText.Split(" ")
For i = 0 To Numbers.Length – 1
Number = CShort(Numbers(i))
ch = Chr(Number Xor Code)
Decrypt = Decrypt & ch
Next
txtNote.Text = Decrypt