Using VB6 to Encrypt and Decrypt Files

By | 2019-02-15

The user will still be able to see the encrypted file, but if someone else logs on that machine and attempts to view the file they will see the encrypted file but not its contents.

It has been possible to encrypt files using built-in function of Windows since the XP days. This example shows how to use this encryption in your VB6 programs.

First, we need to define the functions. Paste these items in to a new module.

Private Declare Function EncryptFile Lib "ADVAPI32" Alias _
   "EncryptFileA" (ByVal lpFileName As String) As Boolean
Private Declare Function DecryptFile Lib "ADVAPI32" Alias _
    "DecryptFileA" (ByVal lpFileName As String, ByVal dwReserved As Long) As Boolean

Public Function Encrypt(ByVal strFileName As String) As Boolean
    Encrypt = (EncryptFile(strFileName) = True)
End Function

Public Function Decrypt(ByVal strFileName As String)
   Decrypt = (DecryptFile(strFileName, 0) = True)
End Function

Example Usage

Create a new form and paste the code above into it. Then add a commandbutton called Command1 and add this code:

Private Sub Command1_Click()
   If Encrypt("c:\temp\MyFile.txt") Then
      MsgBox "It Worked"
   Else
      MsgBox "It Failed"
   End If
End Sub

When you click on the button it will encrypt the file c:\temp\myfile.txt (ensure you create the text file.) You can also decrypt it using the Decrypt function provided.

Update

I’ve added a sample project which includes a basic file browser to select a file to encrypt. There is no error checking in the project; it is simply to show the usage of the encryption and decryption functions.

Encrypt/Decrypt Demo Interface

But how to know if the project is actually working?

There are a couple of ways to do this, but perhaps the simplest is to right click the file in question, and select properties from the context menu. Next, select the Details tab. In the attributes field, you should see a capital letter E, which means the file is encrypted. No E, no encrpytion.

Test File Properties Showing Encryption Enabled

Also, if you have the view enabled, the filename will show as a green color in the Windows Explorer view, as such:

Non-encrypted and encrypted coloring

The top line is the normal file, while the bottom line is the file after encryption.

Attachments

FileUploadedSize
389-20190216-131136-EncryptionAPIDemo.zip2/16/2019 1:11:36 PM1787
Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.