Click here to Skip to main content
Click here to Skip to main content

Base .NET Cryptography Services with Visual Basic 2008

, 13 Mar 2008
Rate this:
Please Sign up or sign in to vote.
Learn how to be the only one accessing your files, with two simple .NET methods.

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:

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:

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.

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.

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:

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:

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)

About the Author

Alessandro Del Sole
Other
Italy Italy
I'm a Microsoft Visual Basic MVP. I'm an Italian .NET developer and I write articles and books about Visual Basic, Visual Studio LightSwitch, and the .NET technologies.
 
Check out my blog at: http://community.visual-basic.it/AlessandroEnglish

Comments and Discussions

 
QuestionOFD1 ?! Pinmemberoctav_jmk26-May-11 10:57 
QuestionWorks with Consumer Versions? PinmemberAlpha Nerd13-Apr-08 7:59 
GeneralAuthorization problem PinmemberWaleed_el_mandouh20-Mar-08 0:38 
I’m trying to decrypt a file and always I have the message, that I’m no authorized to do so, what are the possible reasons for this.
 
This file is in side subfolder in side system32, and it is not read only!!
GeneralRe: Authorization problem PinmemberAlessandro Del Sole20-Mar-08 8:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 13 Mar 2008
Article Copyright 2008 by Alessandro Del Sole
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid