Protecting Visual Basic .NET Source Code and Applications

Protecting Visual Basic.NET Source Code and Applications

With this article, I will explain Obfuscation, Cryptography, and technologies used to protect your Visual Basic.NET applications, once distributed.



Obfuscation is the process of scrambling the symbols, code, and data of a program to prevent reverse engineering. Obfuscation tools mangle symbols and rearrange code blocks to foil decompiling. They also may encrypt strings containing sensitive data. It's important to understand that obfuscators (as they exist today) can't completely protect your intellectual property. Because the code is on the client machine, a really determined hacker with lots of time can study the code and data structures enough to understand what's going on. Obfuscators do provide value in raising the bar, however, defeating most decompiler tools and preventing the casual hacker from stealing your intellectual property. They can make your code as difficult to reverse engineer as optimize native code.


When a well-written obfuscator tool goes to work on readable program instructions, a likely side effect is that the output will not only confuse a human interpreter, it will break a decompiler. While the forward (executable) logic has been preserved, the reverse semantics have been rendered non-deterministic. As a result, any attempt to reverse-engineer the instructions to a 'programming dialect' like C# or VB will likely fail because the translation is ambiguous. Deep obfuscation creates a myriad of decompilation possibilities, some of which might produce incorrect logic if recompiled. The decompiler, as a computing machine, has no way of knowing which of the possibilities could be recompiled with valid semantics. Humans write and employ decompilers to automate decompilation algorithms that are too challenging for the mind to follow. It is safe to say that any obfuscator that confuses a decompiler will pose even more of a deterrent to a less-capable human attempting the same undertaking.

Methods used in obfuscating code

Available Obfuscation Tools




Encryption is the process of translating plain text data (known as plaintext) into something that appears to be random and meaningless (known as ciphertext). Decryption is the process of converting ciphertext back to plaintext.

To encode plaintext, an encryption key is used to impose an encryption algorithm onto the data. To decode cipher, a user must possess the appropriate decryption key. A decryption key consists of a random string of numbers, from 40 through 2,000 bits in length. The key imposes a decryption algorithm onto the data. This decryption algorithm reverses the encryption algorithm, returning the data to plaintext. The longer the encryption key is, the more difficult it is to decode. For a 40-bit encryption key, over one trillion possible decryption keys exist.

There are two primary approaches to encryption: symmetric and public-key. Symmetric encryption is the most common type of encryption and uses the same key for encoding and decoding data. This key is known as a session key. Public-key encryption uses two different keys, a public key and a private key. One key encodes the message and the other decodes it. The public key is widely distributed while the private key is secret.


Cryptography is a way to encrypt and decrypt data. By encrypting data you are protecting your data from other curious users who would like to know the data that is present. If you want to conceal chunks of data, such as connection strings or data written to a database or XML file, you could use Cryptography.

Classes used with Cryptography

System.Security.Cryptography Namespace

Whether you want to protect your source code or not, is up to you at the end of the day, but hopefully you saw that there's much more to just writing programs, and I will advise you to consider ways in which you can protect your source codes.

Protecting Visual Basic .NET Source Code and Applications

Now you may ask: "What is the next step, how can I protect my applications further?" To answer this, I will look at a few methods used to protect your applications against misuse. I will now discuss ADS, and other CD Copy prevention techniques as well as the importance of creating Trial Applications.

Prevent CD Copying Techniques

Alternate Data Streams (ADS)


An alternate data stream is any kind of data that can be attached to a file but not in the file on an NTFS system. The Master File Table of the partition will contain a list of all the data streams that a file contains, and where their physical location on the disk is. Therefore, alternate data streams are not present in the file, but attached to it through the file table. A typical file contains only a single data stream, called $DATA. This is the data contained in the file itself, and is not an alternate data stream because it is the data stream itself.

The convention that Microsoft chose for file naming is the following: filename.extetsion:alternatedatastreamname:$DATA. When you open a file by any normal means, you access the $DATA stream. Because there is no alternate data stream, the file system actually opens filename.extension::$DATA. If, however, this file had an alternate data stream called 'Test', and you wanted to open it, you would have to open filename.extension:Test:$DATA.


ADS are not stored in the file itself. You might be asking yourself 'If I store 1 Mb worth of text into an ADS of a file, will the file become 1 Mb bigger?' The answer is no. Because the data is never stored in the file itself, the APIs to retrieve the size of the file will never take into account the ADS you might've added (or that the OS added). Just as Explorer will display and open only the $DATA data stream (the file itself), Explorer will show only the size of $DATA (the size of the file itself). Explorer is not exhibiting a bug; any application calling the normal Windows API will exhibit the same behavior. So what does this mean? It means you can store 2 Gigabytes of data into the ADS of an empty file and that the OS will display the file as empty. Opening this file with Notepad will result in a blank text page, and even a hex editor would display the file as empty. The 2 Gb would, however, be shaved off your disk, and would you forget the existence of this ADS; only a reformat would reclaim your space. You can use an ADS file just the same as you use a regular file, except that the file is "invisible."

To conclude, you can "attach" an ADS file to your program's EXE file, in the root folder that can be about 1 Gb, even more, in size and it won't show up in the properties for the CD. Then, when you try to copy the CD, it may fail because it is oversized and will not fit on the destination CD.

If you don't think ADS is the answer to your problems, let me briefly explain other technologies used in CD Protection.

Weak Sectors

There is a certain type of CD copy protection that uses "weak sectors." The idea is to make a CD with portions that aren't burned very well, but reading them still works. I guess the burner manufacturers are cooperating with the software/music industry on this. I don't know whether software CDs are being done in the same manner as music CDs, though. Unless I'm mistaken, you can't create this type of protection with a standard burner. There are no doubt CD duplication services that can do it for you, but I suppose you are looking for a solution that you can do yourself. The trouble is, anything you come up with that is based on a software approach will be vulnerable.

Online Registration

However, if you require online registration, and you create a log of all the CD serial numbers, you can have greater control. For instance, if someone installs the software, your Web site receives their registration info, and you now know the software has been installed. A copy of the CD is useless because they can't register it because the serial number is invalid. Your biggest task with this approach is how to issue registration numbers, such that hackers would have a tough time generating a fake one. They would also have to figure out how to bypass your registration dialog, which would idealy prevent the app from being installed/used unless the registration completes successfully. Remember that nothing is foolproof, but this seems like something that would deter "casual" pirating.

Other References

CD Media World

Trial Applications


Trial applications allow only a specified limit in which the application can be used. Once the time limit expires, the application is unusable.


The whole purpose of Trial applications is to let user evaluate your application, but only for a specified time frame. Once the Evaluation period expires, the users must purchase your program.


How exactly can we prevent unauthorised use of our applications?
Well, the first thought that comes to mind would probably be to create Registry entries storing the dates; then, of course, when the Registry date is a specified number of days later than the current date, disallow continuation of the application. Unfortunately, the chance that someone with enough patience can figure out where you saved the information is still there.

What about saving the Registry entries deeper in the Registry, in a more obscure place in the Registry?
That idea might work to prevent people with little patience to figure it out, but it might not work for cracking software.

Okay, let's leave the Registry. Why not store the date values or the number of times the application is accessed in a file?
If you disguise your files well enough, it may work. Take a look at a sample program.

The included example firstly creates a folder named Sys.Dll, and then it sets the folder attributes to Hidden. By setting a file or folder to Hidden, the normal computer user will not see it. However, if you have your computer set up to be able to see hidden files, you will see the folder. A name like Sys.Dll, of course, will make any person think twice about opening it up, and "play around." Have a look at the code that achieves this:

Private Sub CreatFold()    'to create the needed folder, where we
                           'hide the file

   'determine if Sys.dll folder exists, if it doesn't, create it
   Dim folderinfo As New IO.DirectoryInfo(Application.StartupPath _
                                          & "\Sys.dll")

   If folderinfo.Exists = False Then
      MkDir(Application.StartupPath & "\Sys.dll")
      'create Sys.dll folder here

      folderinfo.Attributes = IO.FileAttributes.Hidden
      'hide the folder in my computer
   End If

End Sub

Remember one thing, though. When dealing with IO.DirectoryInfo, you need to import the System.io namespace, as follows:

'import the namespace above the class definition
Imports System.io    'needed when dealing with directoryinfo
Public Class Form1

The next step is to create a file (with an obscure name and extension)—for example, sys.trx—and store the number of times your application is run in that file. If the user has run your application a specified number of times, exit the application. The code follows:

Dim filenumber As Integer        'get value of freefile function.
Dim times_used As Integer = 1    'how many times used, initilaised
Dim max_limit  As Integer = 4    'maximum number of times

Private Sub Trial()

   CreatFold()    'call sub to create folder here first, before
                  'using it in code!

   filenumber = FreeFile()    'We assign the number which
                              'represents which file to open
   If IO.File.Exists(Application.StartupPath & _    'Check if
      "\Sys.dll\sys.trx") Then                       'file exists.
      FileOpen(filenumber, Application.StartupPath & _
               "\Sys.dll\sys.trx", OpenMode.Random, _
      'If exists, open it in readwrite mode.
      FileGet(filenumber, times_used)
      'read values stored from the file. The number of times used
      FileClose(filenumber)    'close the file

      If times_used >= max_limit Then
      'check if the user has used the software more than the limit
         MsgBox("Sorry, Your trial period expired! Please purchase _
                this software", MsgBoxStyle.Critical)
         'if time limit exceeded, then exit
         Application.Exit()    'we exit our app here.
      End If

      times_used = times_used + 1 'increment times used

      FileOpen(filenumber, Application.StartupPath & _
               "\Sys.dll\sys.trx",OpenMode.Random, _
               OpenAccess.ReadWrite)    'store value back
      FilePut(filenumber, times_used)
      'This part is if the user is using the software for the first
      'time. The file has to be created.
      FileOpen(filenumber, Application.StartupPath & _
               "\Sys.dll\sys.trx", OpenMode.Random, _
      FilePut(filenumber, times_used)    'store times used
   End If

End Sub

Private Sub Form1_Load(ByVal sender As Object, _
                       ByVal e As System.EventArgs) _
   Handles MyBase.Load

   Trial()    'call the Trial function here

End Sub

To see the working example in action, download the sample application named TrialApp.zip.

Although my methods of protecting against misuse may not be the best, my goal with this article was just to provide a bigger overview of this topic, and to give you a clearer picture of what steps you can follow when you want to protect your code, as well as your applications.

This article was originally published on April 26th, 2006

About the Author

Hannes du Preez

Hannes du Preez is a Microsoft MVP for Visual Basic. He is a trainer at a South African-based company. He is the co-founder of hmsmp.co.za, a community for South African developers.


Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date