Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Base .NET Cryptography Services with Visual Basic 2008

2.60/5 (2 votes)
13 Mar 2008CPOL2 min read 1   849  
Learn how to be the only one accessing your files, with two simple .NET methods.

Image 1

Introduction

From version 2.0 of Microsoft .NET Framework, the System.IO.File class exposes two very interesting methods which allow to apply to (or remove from) any file a kind of protection so that the file itself can be accessed only by the user who applied the cryptography.

For example, if more than one person can access the same system with different user accounts, some folders are accessible by all users and, consequently, the same is applicable for files which reside inside these folders.

With these methods, we can apply this kind of protection to all files created by our user account, preventing others from accessing them. The methods we’re talking about are System.IO.File.Encrypt and System.IO.File.Decrypt. The full VB 9.0 source code for this article is available from the link above. Just remember that this kind of encryption can be used only on NTFS file systems.

Using the code

After a small introduction, it’s time to write code. I’ve added comments inside the code below, so that reading the article should be a little more fluent. We’re going to create a Windows Forms application which should appear like the above figure. First of all, an Imports directive is required:

VB
Imports System.IO

The following code is assigned to the Browse button, so that the user can select which file to encrypt, and to the OK button:

VB
Private Sub Button2_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Sfoglia.Click

    With OFD1
        .Filter = "All files|*.*"
        .Title = "Select a file to encrypt"
        If .ShowDialog = Windows.Forms.DialogResult.OK And _
                         String.IsNullOrEmpty(.FileName) = False Then
            TextBox1.Text = .FileName
        Else
            Exit Sub
        End If
    End With
End Sub

The following method is called when the encryption terminates, and opens the folder which contains the file itself.

VB
Private Sub OpenFolder()
    Process.Start("Explorer.exe", Path.GetDirectoryName(TextBox1.Text))
End Sub

The following code verifies that a file name has been specified, then calls the appropriate method (Encrypt or Decrypt); otherwise, an error message is shown.

VB
Private Sub Button4_Click(ByVal sender As System.Object, _
           ByVal e As System.EventArgs) Handles Button4.Click

    'If the TextBox contains a valid string...
    If String.IsNullOrEmpty(TextBox1.Text) = False Then
        '...encrypts the related file
        Encrypt(TextBox1.Text)
    Else
        MessageBox.Show("No file specified yet!")
        Exit Sub
    End If
End Sub

Private Sub Button5_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button5.Click
    'If the TextBox contains a valid string...
    If String.IsNullOrEmpty(TextBox1.Text) = False Then
        '...decrypts the related file
        Decrypt(TextBox1.Text)
    Else
        MessageBox.Show("No file specified yet!")
        Exit Sub
    End If
End Sub

The following method applies cryptography to the specified file and manages all possible exceptions for this scenario:

VB
Private Sub Encrypt(ByVal Filename As String)

    Try
        File.Encrypt(Filename)
    Catch ex As ArgumentNullException
        MessageBox.Show("A null argument was specified")
    Catch ex As ArgumentException
        MessageBox.Show("Specified pathname contains invalid characters")
    Catch ex As DriveNotFoundException
        MessageBox.Show("Invalid drive")
    Catch ex As FileNotFoundException
        MessageBox.Show("File not found")
    Catch ex As PathTooLongException
        MessageBox.Show("Pathname too long")
    Catch ex As IOException
        MessageBox.Show("I/O error")
    Catch ex As PlatformNotSupportedException
        MessageBox.Show("You're trying to execute this " & _ 
                        "action onto a non Windows NT operating system")
    Catch ex As NotSupportedException
        MessageBox.Show("Current file system is not NTFS")
    Catch ex As UnauthorizedAccessException
        MessageBox.Show("You're not authorized to execute the selected action")
    End Try

    OpenFolder()
End Sub

As you can easily note, we’ve written more code about managing exceptions than anything! The following code implements the Decrypt method:

VB
Private Sub Decrypt(ByVal Filename As String)
    Try
        File.Decrypt(Filename)
    Catch ex As ArgumentNullException
        MessageBox.Show("A null argument was specified")
    Catch ex As ArgumentException
        MessageBox.Show("Specified pathname contains invalid characters")
    Catch ex As DriveNotFoundException
        MessageBox.Show("Invalid drive")
    Catch ex As FileNotFoundException
        MessageBox.Show("File not found")
    Catch ex As PathTooLongException
        MessageBox.Show("Pathname too long")
    Catch ex As IOException
        MessageBox.Show("I/O error")
    Catch ex As PlatformNotSupportedException
        MessageBox.Show("You're trying to execute this action " & _ 
                        "onto a non Windows NT operating system")
    Catch ex As NotSupportedException
        MessageBox.Show("Current file system is not NTFS")
    Catch ex As UnauthorizedAccessException
        MessageBox.Show("You're not authorized to execute the selected action")
    End Try

    OpenFolder()

End Sub

Both methods work the same way, and the exceptions managed are identical. When cryptography is applied, the file name appears in Explorer as marked in green instead of black. This is just to let the user understand that they are looking at an encrypted document. The color is reversed to black when the file gets decrypted.

What happened to our file?

To check how encryption affects files, you should access the system with another user account (e.g., Guest). Then, try to open the previously encrypted document. If everything works fine, Windows will not let you open the file. To restore the file’s original state, access it with the first user account and decrypt the file.

Points of interest

This is perhaps the simplest way to add protection to files. But encryption in .NET Framework is a very powerful task that you can study much deeper by reading the official MSDN documentation. But if you do need something very fast and easy, Encrypt and Decrypt can be a good choice.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)