Implementing File Compression and Encryption in Visual Basic 6 Using the Microsoft .NET Framework, Part I: Cryptography
Swigart Consulting LLC.
Microsoft Visual Basic 6
Microsoft Visual Basic .NET 2003
Microsoft Visual Basic 2005
Microsoft Visual Studio .NET 2003
Microsoft Visual Studio 2005
Summary: In this two-part article series, you'll see how you can easily add encryption and data compression (ZIP) capabilities to existing Visual Basic 6 applications using the .NET Framework. While encryption and compression may not seem like related technologies, if you think about it, each one takes a set of data and performs a transformation on it. In the case of encryption, the data is made unreadable, and with compression, the data is made smaller. You'll also see that both utilize many of the same underlying technologies. (6 printed pages)
Click here to download the code sample for this article.
To use the code in this article, you will need to install Visual Studio 2005, or the free Visual Basic Express. These products can be installed along side of Visual Studio 6.0, Visual Studio .NET, and/or Visual Studio 2003, without impacting those products.
I have a secret, and I don't want you to know it. Actually, I have an application, and I want it to be able to store information in an encrypted format so that it can't be read by unauthorized users. Visual Basic 6 does not have any built-in functionality to perform encryption or decryption of data, but the Microsoft .NET Framework does have strong encryption built it. In this article, I provide a Visual Basic .NET component that provides encryption and decryption functionality, and you can very easily use this component from Visual Basic 6, ASP, or any other COM environment.
First, it's worth reviewing how Visual Basic 6 lets you work with files. Visual Basic 6 provides a number of language keywords for file I/O.
Example 1. Reading for a file with Visual Basic 6
Dim dataIn As String Open someFileName For Input As #1 Do Until Eof(1) Line Input #1, dataIn Debug.Print dataIn Loop Close #1
With Visual Basic 6, you do all your operations on a file handle (#1 in this case), and it's up to you to manage this file handle. There isn't a single object that encapsulates the file operations; instead, there are a number of keywords (Open, Close, Input, and so on). If you do want to do encryption and decryption with Visual Basic 6, you would have to read all the data into memory, encrypt all of it using some third party component (generating what's known as "cipher text"), and then send all the cipher text to the output file. It would be nice if you could stream the information through your program, but this would not be easy to do.
To facilitate really easy encryption from Visual Basic 6, I've created an excryption/decryption component. Next you'll see how this component was implemented, but it's worth mentioning that you don't need to understand any of the implementation details to actually use the component. If you just want to use the component without digging into how it works, just skip ahead to Visual Basic 6 Cryptography.
Before jumping into encryption, it's important to understand how Visual Basic .NET deals with file IO. The Microsoft .NET Framework uses something known as "streams" when working with files, as shown here.
Example 2. Visual Basic .NET File IO
Dim sw As New StreamWriter("C:\log.txt") sw.WriteLine("This is a test") sw.Close()
You can see that Visual Basic .NET provides classes specifically for reading and writing from files (and other IO devices). In this case, the code uses the StreamWriter class to write lines of text to a file. The StreamWriter object is a nice convenience, as you don't have to keep track of a file handle, and all the operations for working with a file show up in Intellisense. In addition to the StreamWriter class, there are also these classes:
Table 1. Classes available in Visual Basic .NET
|FileStream||Reading and writing from a binary file.|
|NetworkStream||Reading and writing from a network.|
|MemoryStream||Reading and writing from memory as though it were a file.|
In actuality, the StreamWriter in our code sample is internally using a FileStream object to write information to the disk. The FileStream lets you create, open, and append to disk files, and open them for reading and writing. However, the FileStream wants to read and write blocks of data—arrays of bytes—to and from files. When working with text, you typically want to work with lines, not 1024 byte blocks, so the StreamWriter stacks on top of the FileStream to provide the WriteLine functionality. You could also stack the StreamWriter or StreamReader on top of a NetworkStream or MemoryStream so that you could WriteLine or ReadLine from those devices as well.
This is really the strength of streams. You can stack one stream on top of another to plug in additional functionality. In fact, this is how encryption works in Visual Basic .NET. The CryptoStream is added to the stack, and all the data that passes through it is encrypted or decrypted:
Example 3. Stacking streams to enable encryption with Visual Basic.NET
fs = New FileStream(fileName, FileMode.Create, FileAccess.Write) cs = New CryptoStream(fs, rc2.CreateEncryptor(), CryptoStreamMode.Write) sw = New StreamWriter(cs)
Here, a FileStream class is created to enable writing to a specific disk file. A CryptoStream is stacked on top of the FileStream so that information is encrypted before it's sent to the FileStream. The StreamWriter is then stacked on top of the CryptoStream so that you have convenient WriteLine functionality, rather than having to work with fixed length blocks of data.
The CryptoStream is what does the magic of encryption. It supports many encryption algorithms, and so it needs to be configured with some initial information before it's used. For this component, the RC2 encryption algorithm was used, as it provides strong, fast encryption. However, if you want to use DES, Triple-DES, or Rijndael encryption, this code can be modified to use those instead.
Example 4. Configuring RC2 Encryption with Visual Basic.NET
Dim rc2 As New RC2CryptoServiceProvider rc2.IV = IV Dim pdb As New PasswordDeriveBytes(password, Nothing) rc2.Key = pdb.CryptDeriveKey("RC2", "SHA1", 128, IV)
Symmetric cryptography is based on using a secret key to encrypt the information. In this case, the key will be supplied to this algorithm in the form of a password. From the password, a cryptographic key is derived using the PasswordDeriveBytes class. For additional security, an initialization vector can be used (IV). An IV is used to insure that, if a document contains identical sections of plain text, the document doesn't encrypt to identical cipher text. This also makes the key more secure if multiple files are encrypted using the same key. When you use this component, specifying an IV is optional.
Again, while the basics of cryptography are being covered here, you don't need to know anything about .NET or cryptography to use this component. From Visual Basic 6, using this component is as simple as this.
Example 5. Using the cryptography component from Visual Basic 6
Dim e As wrappers.EncryptedFileWriterWrapper Set e = New wrappers.EncryptedFileWriterWrapper e.Open "c:\file.bin", txtPassword, False, "" e.WriteLine (txtMessage) e.Close
You can see that once the EncryptedFileWriterWrapper has been created, it's trivial to use. You just create an instance of it, give it a file name and password, and start writing data. The data will be encrypted and written to the file.
Figure 1. Attempting to view encrypted data with Notepad
Reading and decrypting the data is equally simple.
Example 6. Reading and decrypting data using Visual Basic 6
Dim e As wrappers.EncryptedFileReaderWrapper Set e = New EncryptedFileReaderWrapper e.Open "c:\file.bin", txtPassword, "" While Not e.EOF txtMessage = txtMessage & e.ReadLine & vbCrLf Wend e.Close
Again, you just specify a file name and password, and start reading. The data is decrypted by the component and returned as simple text.
For your convenience, I've put together a Visual Basic 6 application that uses the component to perform encryption and decryption. To use this component, you may need to do a couple of things.
- Download and install the Microsoft .NET Framework SDK 2.0 (if you have Visual Studio .NET 2005 or Visual Basic Express installed, you can skip this step).
- Download the code associated with this article.
- Execute the "Install.bat" file included with the code for this article. This registers the encryption component so that you can use it from your Visual Basic 6 application.
- In the code for this article, open the Visual Basic 6 project in the "Encryption" folder.
- Press F5 to run the sample application:
Figure 2. Sample application for encryption and decryption
Enter any string for the password and click Save. The text is saved to "c:\file.bin." If you open this file in Notepad, you will see that it's encrypted. The textbox is also cleared.
If you click on Load, the information will be retrieved, decrypted, and displayed in the text box. If you change the password so that it doesn't match the password that the text was saved with, you will see that the file is not decrypted.
Visual Basic 6 doesn't provide built in encryption and decryption functionality, but the Microsoft .NET Framework does. As with everything in the .NET Framework, it is relatively simple to expose that functionality so that it can be used from a Visual Basic 6 application. This article provides you with a pre-packaged solution to add encryption and decryption functionality to your Visual Basic 6 application with just a few lines of code. Enjoy.
About the author
Scott Swigart (www.swigartconsulting.net) spends his time consulting, authoring, and speaking about emerging and converging technologies. Scott has worked with a wide range of technologies over his career, beginning with Commodore 64 programming at the age of 12, writing hardware diagnostics for UNIX systems in C++, and building windows desktop, and Web applications. Over the years, Scott has worked with component development, XML technologies, .NET, Web service, and other languages, platforms, and paradigms. With this experience, Scott has seen how technology evolves over time, and is focused on helping organizations get the most out of the technology of today, while preparing for the technology of tomorrow. Scott is also a Microsoft MVP, and co-author of numerous books and articles. Scott can be reached at Scott Swigart.